﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChipTool.Enties;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Configuration;
using System.Diagnostics;
using XChip_Common;
using BinAnalysisHelp;
using Newtonsoft.Json;
using ICSharpCode.SharpZipLib.Zip;
using System.IO.Ports;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using SharpCompress.Readers;

namespace XChipTool
{
    public partial class XChip_ToBin_Security : DevExpress.XtraEditors.XtraUserControl
    {
        #region 全局变量

        /// <summary>
        /// heard 头文件全局变量
        /// </summary>
        public List<xc151> xcBaseList = new List<xc151>();
        //public xc151Manager Xc151BLL;
        public xc151_exManager xc151_exBll;
        public bincurrencyManager Bincurrency_BLL;
        public serialdataManager Serialdata_BLL;
        private string GuidNo;
        //随机因子
        private int randomNo;
        //判断安防或者行车模式
        public bool isSecurity;
        //private string strIniFile = Application.StartupPath + "\\SettingCfg\\XChip461bin.ini";
        private string strSetting1File = Application.StartupPath + "\\SettingCfg\\setting1_XChip.txt";

        //private string strIniFileTxt = Application.StartupPath + "\\SettingCfg\\Xchip151bin.ini";

        IniFiles OLocalIni;

        bool bNeedIni = true;  //生成bin时是否必须有ini文件

        private List<string> lstCryptKeyFile = new List<string>();
        private List<int> lstCryptType = new List<int>();
        List<string> patchheader = new List<string>();
        List<string> codeheader = new List<string>();
        private int MenuLength;
        private int FontLength;
        List<string> DCBLlist;
        private List<string> Pageslist;
        /// <summary>
        /// 创建上下文同步
        /// </summary>
        private SynchronizationContext context;
        /// <summary>
        /// // -1 表示无选着  0 表示案件 1表示adc
        /// </summary>
        public int isPress_key;

        private static XChip_ToBin_Security _instance;
        public SerialPort sPortTemp;
        public static XChip_ToBin_Security Instance(bincurrencyManager _Bincurrency_BLL, serialdataManager _Serialdata_BLL, SerialPort _sPortTemp, bool isOSD)
        {
            if (_instance == null)
            {
                _instance = new XChip_ToBin_Security(_Bincurrency_BLL, _Serialdata_BLL, _sPortTemp, isOSD);
            }
            else
            {
                XChip_ToBin_Security_Load();
            }
            return _instance;
        }

        #endregion
        public XChip_ToBin_Security()
        {
            InitializeComponent();
        }
        public XChip_ToBin_Security(bincurrencyManager _Bincurrency_BLL, serialdataManager _Serialdata_BLL, SerialPort _sPortTemp, bool isOSD)
        {
            Bincurrency_BLL = _Bincurrency_BLL;
            Serialdata_BLL = _Serialdata_BLL;
            isSecurity = isOSD;
            sPortTemp = _sPortTemp;
            InitializeComponent();
        }

        /// <summary>
        /// 表格样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView View = sender as DevExpress.XtraGrid.Views.Grid.GridView;

            if (e.Column.FieldName == "FileStatusMsg")
            {
                e.Appearance.ForeColor = Color.White;
                if (e.CellValue.ToString().Contains("请加载文件"))
                {
                    e.Appearance.BackColor = Color.Yellow;
                    e.Appearance.ForeColor = Color.Black;
                }
                else if (e.CellValue.ToString().Contains("异常文件"))
                {
                    e.Appearance.BackColor = Color.Red;
                }
                else if (e.CellValue.ToString().Contains("文件处理中"))
                {
                    e.Appearance.BackColor = Color.LightPink;
                }
                else if (e.CellValue.ToString().Contains("文件正常"))
                {
                    e.Appearance.BackColor = Color.Green;
                }
            }
        }

        private void gridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            var aa = gridView1.GetRowCellValue(e.RowHandle, "SectionName").ToString();
            if (gridView1.GetRowCellValue(e.RowHandle, "SectionName").ToString().ToLower().Contains("patch".ToLower()) && e.Column.FieldName == "OpenFileButton")
            {
                var ributtonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                ributtonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                ributtonEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                ributtonEdit.Buttons[0].Visible = true;
                ributtonEdit.Buttons[0].Caption = "打开文件";
                ributtonEdit.ButtonClick += OpenFile_ButtonClick;
                e.RepositoryItem = ributtonEdit;
            }
            else if (gridView1.GetRowCellValue(e.RowHandle, "SectionName").ToString().ToLower().Contains("setting".ToLower()) && e.Column.FieldName == "OpenFileButton")
            {
                var ributtonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                ributtonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                ributtonEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                ributtonEdit.Buttons[0].Visible = true;
                ributtonEdit.Buttons[0].Caption = "打开文件夹";
                ributtonEdit.ButtonClick += OpenFile_ButtonClick;
                e.RepositoryItem = ributtonEdit;
            }
        }

        private void OpenFile_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                var row = gridView1.GetSelectedRows();
                var Id = gridView1.GetRowCellValue(row[0], "Id").ToString();
                var guid = gridView1.GetRowCellValue(row[0], "GuidId").ToString();
                //传入Id获取一个bincurrency_extend对象实体 执行了数据库的查询bincurrency_extend改为bincurrency_export
                bincurrency_export binmodel = Bincurrency_BLL.GetModel(int.Parse(Id), guid);
                if (binmodel.SectionGiven.Contains("Header"))
                {
                    return;
                }

                SetShowMsg($"导入名称：{binmodel.SectionName}");

                if (binmodel.SectionGiven.Contains("Setting"))
                {
                    //bNeedIni = Convert.ToBoolean(int.Parse(GetConfigValue("xcCreateBinNeedIni")));

                    //XChip_SecurityFile SecurityFile = new XChip_SecurityFile(binmodel);
                    //SecurityFile.SendBinSetMsg += ToolBinSetting151_SendBinSetMsg;
                    //SecurityFile.StartPosition = FormStartPosition.CenterParent;
                    //SecurityFile.ShowDialog();

                    //XChip_SecurityFile SecurityFile = new XChip_SecurityFile();
                    //SecurityFile.SendBinSetMsg += ToolBinSetting151_SendBinSetMsg;
                    //SecurityFile.StartPosition = FormStartPosition.CenterParent;
                    //SecurityFile.ShowDialog();
                    //XChip_SecurityFile SecurityFile = new XChip_SecurityFile(binmodel);
                    //SecurityFile.StartPosition = FormStartPosition.CenterParent;
                    //SecurityFile.ShowDialog();
                    if (isUSB.Checked)
                    {
                        XChip_SecurityFile SecurityFile = new XChip_SecurityFile(binmodel);
                        SecurityFile.StartPosition = FormStartPosition.CenterParent;
                        SecurityFile.ShowDialog();
                    }
                    else
                    {
                        isPress_key = pollingcheck.Checked ? radioGroup1.SelectedIndex : -1;
                        XChip_SettingSecurity SecurityFile = new XChip_SettingSecurity(binmodel, osdcheck.Checked, Pageslist, sPortTemp, isPress_key);
                        SecurityFile.SendBinSetMsg += ToolBinSetting151_SendBinSetMsg;
                        SecurityFile.StartPosition = FormStartPosition.CenterParent;
                        SecurityFile.ShowDialog();
                    }



                }
                else if (binmodel.SectionGiven.Contains("config"))
                {
                    //OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    //openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                    //if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
                    //var parentDirectory = Directory.GetParent(openFileDialog1.FileName).FullName;
                    //var filePaths = Directory.GetFiles(parentDirectory, "*.txt").ToArray();

                    //foreach (string item in filePaths)
                    //{
                    //    if (item.Contains("config0"))
                    //    {
                    //        Bincurrency_BLL.Delete(c => c.BinId == 2);
                    //        bincurrency model = new bincurrency();
                    //        model.GuidId = GuidNo;
                    //        model.BinId = 2;
                    //        model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    //        model.BinInPath = item;
                    //        model.BinInName = Path.GetFileName(item);
                    //        var pathNameout = config_Files_For_Header_Patch_Tool(item, true, "", true, false);
                    //        model.BinOutName = Path.GetFileName(pathNameout);
                    //        model.BinOutPath = pathNameout;
                    //        model.FileStatus = 2;
                    //        model.SerialNo = 0;
                    //        model.SortOrder = 0;
                    //        model.IsModified = 1;
                    //        model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                    //        Bincurrency_BLL.Insert(model);
                    //    }
                    //    else if(item.Contains("config1"))
                    //    {
                    //        Bincurrency_BLL.Delete(c => c.BinId == 3);
                    //        bincurrency model = new bincurrency();
                    //        model.GuidId = GuidNo;
                    //        model.BinId = 3;
                    //        model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    //        model.BinInPath = item;
                    //        model.BinInName = Path.GetFileName(item);
                    //        var pathNameout = config_Files_For_Header_Patch_Tool(item, true, "", true, false);
                    //        model.BinOutName = Path.GetFileName(pathNameout);
                    //        model.BinOutPath = pathNameout;
                    //        model.FileStatus = 2;
                    //        model.SerialNo = 1;
                    //        model.SortOrder = 0;
                    //        model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                    //        Bincurrency_BLL.Insert(model);

                    //        var list = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 2);
                    //        var mode = list.Find(c => c.IsModified == 1);
                    //        mode.FileStatus = 2;
                    //        Bincurrency_BLL.Update(mode);
                    //    }
                    //}
                    ConfigFile configFile = new ConfigFile(binmodel);
                    configFile.StartPosition = FormStartPosition.CenterParent;
                    configFile.ShowDialog();
                    //RefreshGridView();
                }
                else if (binmodel.SectionGiven.Contains("Key"))
                {
                    KeyOpen();
                }
                else if (binmodel.SectionGiven.Contains("PUCT"))
                {
                    OpenFileDialog sfd = new OpenFileDialog();
                    //设置文件类型 
                    sfd.Filter = "TXT文件（*.txt）|*.txt";

                    //设置默认文件类型显示顺序 
                    sfd.FilterIndex = 1;

                    //保存对话框是否记忆上次打开的目录 
                    sfd.RestoreDirectory = true;
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        Bincurrency_BLL.Delete(c => c.BinId == 13);
                        bincurrency model = new bincurrency();
                        model.GuidId = GuidNo;
                        model.BinId = 13;
                        model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        model.BinInPath = sfd.FileName;
                        model.BinInName = Path.GetFileName(sfd.FileName);
                        var pathNameout = PUCT_Flash(sfd.FileName);
                        model.BinOutName = Path.GetFileName(pathNameout);
                        model.BinOutPath = pathNameout;
                        model.FileStatus = 2;
                        model.SerialNo = 0;
                        model.SortOrder = 0;
                        model.IsModified = 1;
                        model.LengthAddress = "1000";
                        Bincurrency_BLL.Insert(model);
                    }

                }
                else if (binmodel.SectionGiven.Contains("DCBL"))
                {
                    //OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    //openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                    //if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
                    //var parentDirectory = Directory.GetParent(openFileDialog1.FileName).FullName;
                    ////这个是选择文件夹路径下所有的.jpg图片的路径
                    //var filePaths = Directory.GetFiles(parentDirectory, "*.jpg").ToArray();
                    ////这个是要生成TXT文本的路径
                    //var fileDCBL = Path.GetFullPath(".") + "\\Lib\\fileDCBL.txt";
                    ////下面是dll调用

                    ////调用完毕之后添加数据库
                    //Bincurrency_BLL.Delete(c => c.BinId == 14);
                    //bincurrency model = new bincurrency();
                    //model.GuidId = GuidNo;
                    //model.BinId = 14;
                    //model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    //model.BinInPath = fileDCBL;
                    //model.BinInName = Path.GetFileName(fileDCBL);
                    //model.BinOutName = Path.GetFileName(fileDCBL);
                    //model.BinOutPath = fileDCBL;
                    //model.FileStatus = 2;
                    //model.SerialNo = 0;
                    //model.SortOrder = 0;
                    //model.IsModified = 1;
                    //model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                    //Bincurrency_BLL.Insert(model);
                    DynamicReversingLine SecurityFile = new DynamicReversingLine(binmodel, ref DCBLlist);
                    SecurityFile.StartPosition = FormStartPosition.CenterParent;
                    SecurityFile.ShowDialog();

                }
                else if (binmodel.SectionGiven.Contains("OSD"))
                {

                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                    if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
                    SettingTo151_Help.ClearSetTips151();
                    SettingToTve151.setTips151clear();
                    //清空数组
                    List<string> listStr = File.ReadAllLines(openFileDialog1.FileName, Encoding.Default).ToList();
                    AppHelper.UpdateAppConfig("Folder_Road_Force_Setting", Path.GetDirectoryName(openFileDialog1.FileName));
                    if (osdCZcheck.Checked)
                    {
                        Bincurrency_BLL.Delete(c => c.BinId == 10);

                        bincurrency model = new bincurrency();
                        model = new bincurrency();
                        model.BinId = 10;
                        model.GuidId = GuidNo;
                        model.IsModified = 1;
                        model.SerialNo = 0;
                        model.SortOrder = 0;
                        model.FileStatus = 2;
                        model.Reorder = 5;
                        //var resetPathout = Copy_Files_For_Header_Patch_Tool(resetPath, true, "", true, false);
                        //model.BinOutPath = resetPathout;
                        //model.BinOutName = System.IO.Path.GetFileName(resetPathout);
                        model.BinOutPath = openFileDialog1.FileName;
                        model.BinOutName = System.IO.Path.GetFileName(openFileDialog1.FileName);
                        model.BinInPath = openFileDialog1.FileName;
                        model.BinInName = System.IO.Path.GetFileName(openFileDialog1.FileName);
                        model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                        model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        Bincurrency_BLL.Insert(model);
                        
                    }
                    else
                    {

                        //获取第一行数据进行解析
                        var sList = listStr[0].Split(new char[] { ',', '/', '_' });
                        //菜单数量
                        int MenuNumber = int.Parse(sList[3]);
                        //语言数量
                        int LanguageNumber = int.Parse(sList[4]);
                        //是否勾选版本好
                        bool Isversion = sList[5] == "0" ? true : false;
                        //字体大小
                        int Fontsize = 0;
                        if (!sList[6].Contains("0x"))
                        {
                            Fontsize = int.Parse(sList[6]);
                        }
                        //版本信息页数
                        Pageslist = new List<string>();
                        Pageslist.Add(sList[7]);
                        //语言信息页数
                        Pageslist.Add(sList[8]);
                        //菜单数量后需要计算出菜单结构体的长度 和 字体长度  并更新  
                        MenuLength = MenuNumber * 0xAF0; //844*4—》700*4
                        if (Fontsize == 24)
                        {
                            //24X24
                            FontLength = MenuNumber * 0x1440;
                        }
                        else
                        {
                            //32X32
                            FontLength = MenuNumber * 0x2400;//1024*9
                        }
                        List<string> chuangshuList = new List<string>();

                        List<string> zhishiList = new List<string>();

                        var tMode = VideoHelper.GetTransferMode();
                        var vMode = VideoHelper.GetVideoMode();
                        foreach (var item in sList)
                        {
                            if (tMode.Exists(c => c.Hex == item))
                            {
                                chuangshuList.Add(tMode.Find(c => c.Hex == item).Name);
                            }
                            if (vMode.Exists(c => c.Hex == item))
                            {
                                zhishiList.Add(vMode.Find(c => c.Hex == item).Name);
                            }
                        }
                        int tempNum = 0;

                        //赋值Tips
                        for (int i = 0; i < chuangshuList.Count; i++)
                        {
                            for (int j = 0; j < 12; j++)
                            {
                                if (j < zhishiList.Count)
                                {
                                    SettingTo151_Help.SetTips151[tempNum] = new SettingFile
                                    {
                                        SettingNo = (tempNum + 1).ToString(),
                                        TransferName = chuangshuList[i],
                                        TransferHex = tMode.Find(c => c.Name == chuangshuList[i]).Hex,
                                        VideoName = zhishiList[j],
                                        VideoHex = vMode.Find(c => c.Name == zhishiList[j]).Hex,
                                        patternNo = i,
                                        formatNo = j,
                                        LanguageNo = LanguageNumber,
                                        MenuNo = MenuNumber,
                                        IsVersion = Isversion,
                                        Standarddisplay = true,
                                        TipsSettingNo = $"{tempNum / 32 }_{tempNum % 32 }",
                                    };

                                    SettingToTve151.SetTips151[tempNum] = new SettingFileNew
                                    {
                                        SettingNo = (tempNum + 1).ToString(),
                                        TransferName = chuangshuList[i],
                                        TransferHex = tMode.Find(c => c.Name == chuangshuList[i]).Hex,
                                        VideoName = zhishiList[j],
                                        VideoHex = vMode.Find(c => c.Name == zhishiList[j]).Hex,
                                        patternNo = i,
                                        formatNo = j,
                                        LanguageNo = LanguageNumber,
                                        MenuNo = MenuNumber,
                                        IsVersion = Isversion,
                                        Standarddisplay = true,
                                        TipsSettingNo = $"{tempNum / 32 }_{tempNum % 32 }",
                                    };

                                }


                                SettingTo151_Help.SetTips151[tempNum].hexNote = $"[ 7: 0]OSDVideoRelation[{i}][{j}]";
                                SettingTo151_Help.SetTips151[tempNum].hexAddr = 0x55F4 + Convert.ToUInt32(tempNum); //设置起始地址    

                                SettingToTve151.SetTips151[tempNum].hexNote = $"[ 7: 0]OSDVideoRelation[{i}][{j}]";
                                SettingToTve151.SetTips151[tempNum].hexAddr = 0x55F4 + Convert.ToUInt32(tempNum); //设置起始地址    
                                tempNum++;
                            }
                        }


                        var strList = listStr.Where((c, index) => index < 36).ToList();
                        var savaPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\save_exit.txt";
                        var resetPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\reset.txt";
                        File.WriteAllLines(savaPath, strList);
                        File.WriteAllLines(resetPath, strList);
                        var midListStr = listStr.Where((c, index) => index > 35).ToList();
                        var menuPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\Menu_Font_{DateTime.Now.ToString("yyyyMMddHHmmss")}.txt";
                        File.WriteAllLines(menuPath, midListStr, Encoding.Default);

                        //var listBll = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 10);
                        Bincurrency_BLL.Delete(c => c.BinId == 10);

                        bincurrency model = new bincurrency();
                        model.BinId = 10;
                        model.GuidId = GuidNo;
                        model.IsModified = 1;
                        model.SerialNo = 0;
                        model.SortOrder = 0;
                        model.FileStatus = 2;
                        model.BinInName = System.IO.Path.GetFileName(menuPath);
                        model.BinInPath = menuPath;
                        //var pathNameout = Copy_Files_For_Header_Patch_Tool(menuPath, true, "", true, false);
                        //model.BinOutPath = pathNameout;
                        //model.BinOutName = System.IO.Path.GetFileName(pathNameout);
                        model.BinOutPath = menuPath;
                        model.BinOutName = System.IO.Path.GetFileName(menuPath);
                        model.LengthAddress = ((MenuLength * LanguageNumber) + (FontLength * LanguageNumber)).ToString("X4");
                        //更改用来存储菜单长度字体长度 语言套数  用于bin生成计算
                        model.BinAddressNo = MenuLength.ToString("X4");
                        model.BinAddressOutName = FontLength.ToString("X4");
                        model.Reorder = LanguageNumber;
                        model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        Bincurrency_BLL.Insert(model);

                        model = new bincurrency();
                        model.BinId = 10;
                        model.GuidId = GuidNo;
                        model.IsModified = 0;
                        model.SerialNo = 1;
                        model.SortOrder = 0;
                        model.FileStatus = 2;
                        model.Reorder = 5;
                        model.BinInName = System.IO.Path.GetFileName(savaPath);
                        model.BinInPath = savaPath;
                        //var savaPathout = Copy_Files_For_Header_Patch_Tool(savaPath, true, "", true, false);
                        //model.BinOutPath = savaPathout;
                        //model.BinOutName = System.IO.Path.GetFileName(savaPathout);
                        model.BinOutPath = savaPath;
                        model.BinOutName = System.IO.Path.GetFileName(savaPath);
                        model.LengthAddress = "1000";
                        model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        Bincurrency_BLL.Insert(model);

                        model = new bincurrency();
                        model.BinId = 10;
                        model.GuidId = GuidNo;
                        model.IsModified = 0;
                        model.SerialNo = 2;
                        model.SortOrder = 0;
                        model.FileStatus = 2;
                        model.Reorder = 5;
                        //var resetPathout = Copy_Files_For_Header_Patch_Tool(resetPath, true, "", true, false);
                        //model.BinOutPath = resetPathout;
                        //model.BinOutName = System.IO.Path.GetFileName(resetPathout);
                        model.BinOutPath = resetPath;
                        model.BinOutName = System.IO.Path.GetFileName(resetPath);
                        model.BinInPath = resetPath;
                        model.BinInName = System.IO.Path.GetFileName(resetPath);
                        model.LengthAddress = "1000";
                        model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        Bincurrency_BLL.Insert(model);
                        #region 废除

                        //int iFileCount = 0;
                        //FolderBrowserDialog FolderDialog = new FolderBrowserDialog();
                        //FolderDialog.Description = "请选择一个目录作为路径：";
                        //FolderDialog.ShowNewFolderButton = false;
                        //if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["defaultSetting3Path"]))
                        //{
                        //    FolderDialog.RootFolder = Environment.SpecialFolder.MyComputer;
                        //}
                        //else
                        //{
                        //    FolderDialog.SelectedPath = ConfigurationManager.AppSettings["defaultSetting3Path"];
                        //}

                        //if (DialogResult.OK == FolderDialog.ShowDialog())
                        //{
                        //    string pSavePath = FolderDialog.SelectedPath; //获取文件路径
                        //    DirectoryInfo theFolder = new DirectoryInfo(pSavePath);
                        //    FileInfo[] thefileInfo = theFolder.GetFiles("*.txt*", SearchOption.TopDirectoryOnly);
                        //    List<string> listFile0 = new List<string>();
                        //    bool b_Flash = false;
                        //    bool b_Font = false;
                        //    bool b_menu = false;
                        //    bool b_resetData = false;
                        //    foreach (FileInfo NextFile in thefileInfo)  //遍历文件
                        //    {
                        //        if (NextFile.Name.Contains("OSD_Flash"))
                        //        {
                        //            listFile0.Add(NextFile.FullName);
                        //            b_Flash = true;
                        //        }

                        //        if (NextFile.Name.Contains("OSD_Font"))
                        //        {
                        //            listFile0.Add(NextFile.FullName);
                        //            b_Font = true;
                        //        }

                        //        if (NextFile.Name.Contains("OSD_Menu"))//
                        //        {
                        //            listFile0.Add(NextFile.FullName);
                        //            b_menu = true;
                        //        }

                        //        if (NextFile.Name.Contains("OSD_ResetData"))//OSD_FlashOut
                        //        {
                        //            listFile0.Add(NextFile.FullName);
                        //            b_resetData = true;
                        //        }
                        //    }

                        //    if (b_Flash == false || b_Font == false || b_menu == false || b_resetData == false)
                        //    {
                        //        XtraMessageBox.Show("缺少（OSD_Flash、OSD_Font、OSD_Menu、OSD_ResetData）必要文件！");
                        //        b_Flash = false;
                        //        b_Font = false;
                        //        b_menu = false;
                        //        b_resetData = false;
                        //        return;
                        //    }

                        //    if (listFile0.Count > 0)
                        //    {
                        //        var listBll = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 10);
                        //        List<bincurrency> modelLIst = new List<bincurrency>();
                        //        bincurrency modet;
                        //        for (int j = 0; j < listFile0.Count; j++)
                        //        {
                        //            binmodel = new bincurrency_export();
                        //            binmodel.BinId = 10;
                        //            binmodel.GuidId = GuidNo;
                        //            binmodel.IsModified = 0;
                        //            binmodel.SerialNo = j;
                        //            binmodel.SortOrder = binmodel.SerialNo;
                        //            binmodel.FileStatus = 2;
                        //            binmodel.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        //            //SettxtToEdit0(listNum0[j], listFile0[j]);
                        //            if (!listBll.Exists(c => c.SerialNo == binmodel.SerialNo))
                        //                modelLIst.Add(binmodel);
                        //        }

                        //        Bincurrency_BLL.Insert(modelLIst);

                        //        for (int i = 0; i < listFile0.Count; i++)
                        //        {
                        //            var model = Bincurrency_BLL.GetSingle(c => c.GuidId == GuidNo && c.SerialNo == i && c.BinId == 10);

                        //            model.BinInPath = Path.GetDirectoryName(listFile0[i]);
                        //            model.BinInName = Path.GetFileName(listFile0[i]);
                        //            string strFileName = System.IO.Path.GetFileName(listFile0[i]); //获取文件名
                        //            string path = Application.StartupPath + "\\Lib\\Flash_" + strFileName;
                        //            //if (strFileName.Contains("OSD_Menu"))   //menu内容改小端
                        //            //{
                        //            //Setting2FlashE2prom.CreatNewSmall(listFile0[i], path);
                        //            //}
                        //            //else 
                        //            //{
                        //            System.IO.File.Copy(listFile0[i], path, true);
                        //            //}

                        //            //path :输出文件的全路径
                        //            //var path = Copy_Files_For_Header_Patch_Tool(listFile0[i], true, "", true, false);
                        //            model.BinOutName = System.IO.Path.GetFileName(path); //获取文件名
                        //            model.BinOutPath = path;
                        //            model.FileStatus = 2;
                        //            //文件长度
                        //            model.LengthAddress = FilePathLengthComplement(path);
                        //            Bincurrency_BLL.Update(model);
                        //        }

                        //        var list = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 10);

                        //        Bincurrency_BLL.Update(list);
                        //        //bLoad = true;
                        //    }
                        //}

                        #endregion
                    }
                    if (Setting0_0.Checked)
                    {
                        Setting0_0.Checked = false;
                        Setting0_0.Checked = true;
                    }

                }
                else
                {
                    OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    if (binmodel.BinId == 4 || binmodel.BinId == 5)
                    {
                        openFileDialog1.Filter = "TXT Files(*.bin)|*.bin|All Files(*.*)|*.*";
                        //openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                        if (binmodel.BinId == 4 && GetConfigValue("Patchisxfw") == "0")
                        {
                            openFileDialog1.Filter = "TXT Files(*.xfw)|*.xfw|All Files(*.*)|*.*";
                        }
                    }
                    else
                    {
                        openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                    }
                    string strBinPath = "";
                    if (ConfigurationManager.AppSettings.AllKeys.Contains("Folder_Road_Force_Setting"))
                    {
                        strBinPath = GetConfigValue("Folder_Road_Force_Setting");
                    }
                    else
                    {
                        strBinPath = GetConfigValue("Folder_Road_Force");
                    }
                    openFileDialog1.InitialDirectory = strBinPath;
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        //WaitBefore.Start("请耐心等待...", "正在努力工作中");
                        if (binmodel.BinId == 4 && GetConfigValue("Patchisxfw") == "0")
                        {
                            //var aaa = openFileDialog1.FileName;
                            var binFile =   UnZipFile(openFileDialog1.FileName,"patch");
                            //string[] binFiles = Directory.GetFiles($"{Application.StartupPath}\\Lib\\XChip_Zip", "*.bin", SearchOption.AllDirectories);
                            if (string.IsNullOrEmpty(binFile))
                            {
                                SetShowMsg($"生成错误信息：文件异常缺少");
                                Close_Process_ByAll();
                                //WaitBefore.Close();
                                return;
                            }
                            //string firstMatch = binFiles.FirstOrDefault(s => s.Contains("Patch_Bin"));
                            AppHelper.UpdateAppConfig("Folder_Road_Force_Setting", Path.GetDirectoryName(openFileDialog1.FileName));
                            openFileDialog1.FileName = binFile;
                        }
                        //pSavePath 打开文件不带文件名的 绝对路径
                        //pLocalName 打开文件的 文件名
                        string pSavePath = System.IO.Path.GetDirectoryName(openFileDialog1.FileName); //获取文件路径
                        string pLocalName = System.IO.Path.GetFileName(openFileDialog1.FileName); //获取文件名
                        if (pLocalName.Contains(" "))
                        {
                            SetShowMsg($"选择的文件名不能包含空格!");
                            //WaitBefore.Close();
                            return;
                        }
                       
                        if (binmodel.BinId == 4 || binmodel.BinId == 5)//patch
                        {
                            binmodel.BinInPath = openFileDialog1.FileName;
                            binmodel.BinInName = pLocalName;
                            binmodel.FileStatus = 1;

                            var path = patch_Copy_Files_For_Header_Patch_Tool(openFileDialog1.FileName, true, "", true, false, (int)binmodel.BinId);
                            binmodel.BinOutName = System.IO.Path.GetFileName(path); //获取文件名
                            binmodel.BinOutPath = path;
                            binmodel.FileStatus = 2;
                            //文件长度
                            binmodel.LengthAddress = FilePathLengthComplement(path);
                            Bincurrency_BLL.Update(binmodel);
                            SetShowMsg($"名称：{binmodel.SectionName} \r\n 文件路径：{binmodel.BinOutPath}");
                        }
                        else
                        {
                            binmodel.BinInPath = openFileDialog1.FileName;
                            binmodel.BinInName = pLocalName;
                            binmodel.FileStatus = 1;

                            var path = Copy_Files_For_Header_Patch_Tool(openFileDialog1.FileName, true, "", true, false);
                            binmodel.BinOutName = System.IO.Path.GetFileName(path); //获取文件名
                            binmodel.BinOutPath = path;
                            binmodel.FileStatus = 2;
                            //文件长度
                            binmodel.LengthAddress = FilePathLengthComplement(path);
                            Bincurrency_BLL.Update(binmodel);
                            SetShowMsg($"名称：{binmodel.SectionName} \r\n 文件路径：{binmodel.BinOutPath}");
                        }
                    }
                }

                RefreshGridView();
                AutomaticAddress(guid);
            }
            catch (Exception ex)
            {
                SetShowMsg($"生成错误信息：{ex.Message.ToString()}");
                Close_Process_ByAll();
            }
            finally
            {
                //WaitBefore.Close();
            }
        }
        #region 各种方法

        #endregion
        /// <summary>
        /// Setting2Flash，生成中间Flash文件
        /// </summary>
        /// <param name="Inputfilepath">文本路径</param>
        /// <param name="Isflash">是flash版本还eeprom版本</param>
        /// <param name="eepromaddr">eeprom值</param>
        /// <param name="isSetting">区分是setting栏还是其他栏</param>
        public string Copy_Files_For_Header_Patch_Tool(string Inputfilepath, bool Isflash, string eepromaddr, bool isSetting, bool isHead)
        {
            string strFileName = System.IO.Path.GetFileName(Inputfilepath); //获取文件名
            string strNewSavePath = Application.StartupPath + "\\Lib\\xc151_setting\\Flash_" + strFileName;
            if (isHead)
            {
                Setting2FlashE2prom.FlashHeader2Flash(Inputfilepath, strNewSavePath);
            }
            else
            {
                Setting2FlashE2prom.FlashSetting2Flash(Inputfilepath, strNewSavePath, 1, 0, 0);
            }

            return strNewSavePath;
        }
        public string patch_Copy_Files_For_Header_Patch_Tool(string Inputfilepath, bool Isflash, string eepromaddr, bool isSetting, bool isHead, int bin_Id)
        {
            string strFileName = System.IO.Path.GetFileName(Inputfilepath); //获取文件名
            strFileName = strFileName.Replace("bin", "txt");
            string strNewSavePath = Application.StartupPath + "\\Lib\\xc151_header\\Flash_" + strFileName;
            //strNewSavePath = "C:\\vsProject\\XChip_Bin&Setting_151\\XChipTool_460\\bin\\Debug\\Lib\\Flash_Code_XC151_patch.txt";
            string bin_str = "";
            string bin_mid = "";
            string header_str = "";
            byte[] binchar = new byte[] { };
            //byte[] binchar1 = new byte[] { };
            int file_len;
            FileStream fileStream = new FileStream(Inputfilepath, FileMode.Open);
            //读二进制文件类
            BinaryReader br = new BinaryReader(fileStream, Encoding.UTF8);
            //获取bin文件长度
            file_len = (int)fileStream.Length;
            //得到所有字节
            binchar = br.ReadBytes(file_len);
            int ii = 0;
            int iheader = 0;
            ////清空之前存储的patch头;
            //if (patchheader.Count !=0)
            //{
            //    patchheader.Clear();
            //} 
            foreach (byte j in binchar)
            {
                if (iheader < 16)//将patch头16字节剔除出来并保存至list容器中；
                {
                    header_str = j.ToString("X2");
                    if (bin_Id == 4)
                    {
                        if (patchheader.Count == 16)
                        {
                            patchheader.Clear();
                        }
                        patchheader.Add(header_str);
                    }
                    else //code
                    {
                        if (codeheader.Count == 16)
                        {
                            codeheader.Clear();
                        }
                        codeheader.Add(header_str);
                    }

                    iheader++;
                }
                else
                {
                    ////如果选择小端否则大端;
                    //if (litterbigstr.Checked)//大端
                    //{
                    if (ii < 4)//每四个组成一个中间字符串；
                    {
                        if (ii == 3)
                        {
                            bin_str += "0x" + j.ToString("X2") + "," + "\r\n";
                            ii = 0;
                        }
                        else
                        {

                            bin_str += j.ToString("X2");
                            ii++;
                        }
                    }
                }
            }

            //添加crc校验;
            byte[] newArray = new byte[binchar.Length - 16];
            Array.Copy(binchar, 16, newArray, 0, newArray.Length);
            UInt16 crc_check = Setting2FlashE2prom.XchipCrcCheck16(0xFFFF, newArray);
            uint crc_Reg = (uint)((0xfffc << 16) + crc_check);
            string crc_str = crc_Reg.ToString("X8");
            string crc_str1 = SetLitter(crc_str);
            bin_str += "0x" + crc_str1 + "," + "\r\n";
            //关闭 BinaryReader 对象和基础流
            br.Close();
            System.IO.File.WriteAllText(strNewSavePath, bin_str);
            //也可以指定编码方式
            //System.IO.File.WriteAllText(strNewSavePath, bin_str, Encoding.UTF8);

            //patch长度多了四个字节，因为在中间文件尾部加了四个字节得校验;
            if (bin_Id == 4)
            {
                string lenth = FilePathLengthComplement8(strNewSavePath);
                int a = Convert.ToInt32(lenth, 16);
                int inew = a - 4;
                lenth = inew.ToString("X8");
                patchheader[0] = lenth.Substring(0, 2);
                patchheader[1] = lenth.Substring(2, 2);
                patchheader[2] = lenth.Substring(4, 2);
                patchheader[3] = lenth.Substring(6);
            }


            return strNewSavePath;
        }
        /// <summary>
        /// 更具文件路劲 获取文件长度
        /// </summary>
        /// <param name="mpath">16进制字符串</param>
        /// <returns></returns>
        public string FilePathLengthComplement(string mpath)
        {
            int tempLength = File.ReadAllLines(mpath).Length;
            var tempCount = Convert.ToUInt32((tempLength * 4).ToString("x4"), 16);
            return tempCount.ToString("X4");
        }
        public string FilePathLengthComplement8(string mpath)
        {
            int tempLength = File.ReadAllLines(mpath).Length;
            var tempCount = Convert.ToUInt32((tempLength * 4).ToString("x4"), 16);
            return tempCount.ToString("X8");
        }
        private string GetConfigValue(string strKey)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            return settings[strKey].Value;
        }
        public static string SetLitter(string strold)
        {
            string str1 = strold.Substring(0, 2);
            string str2 = strold.Substring(2, 2);
            string str3 = strold.Substring(4, 2);
            string str4 = strold.Substring(6);
            strold = str4 + str3 + str2 + str1;
            return strold;
        }
        public static void setDataexample(string address, bool Checked, ref List<xc151> XcBaseList)
        {
            if (null != XcBaseList)
            {
                XcBaseList.ForEach(c =>
                {
                    if (c.address == address)
                    {
                        c.dataexample = Checked ? "0x01" : "0x00";
                        return;
                    }
                });
            }
        }
        #region 自动关闭进程
        /// <summary>
        /// 自动关闭进程
        /// </summary>
        public void Close_Process_ByAll()
        {
            Process[] myprocess = Process.GetProcesses();
            foreach (Process p in myprocess)
            {
                //此处需要手动添加app.config 文件下名称
                if (
                   p.ProcessName.Contains(ConfigurationManager.AppSettings["xc151_setting"])
                    || p.ProcessName.Contains(ConfigurationManager.AppSettings["xc151_header"])
                    || p.ProcessName.Contains("cmd")
                    || p.ProcessName.Contains("conhost")
                    || p.ProcessName.Contains("Windows Command Processor"))
                {
                    //p.CloseMainWindow();
                    p.Close();
                    // p.Kill();
                }
            }
        }
        #endregion
        #region 自动计算地址
        public void AutomaticAddress(string guid)
        {
            var list = Bincurrency_BLL.GetListToDefault(guid).Where(c => !string.IsNullOrEmpty(c.BinInPath) || !string.IsNullOrEmpty(c.LengthAddress)).OrderBy(c => c.BinId).ThenBy(c => c.SerialNo).ToList();
            for (int i = 0; i < list.Count; i++)
            {
                if (i == 0)
                    continue;

                if (string.IsNullOrEmpty(list[i - 1].Address) || string.IsNullOrEmpty(list[i - 1].LengthAddress))
                    continue;
                if (list[i - 1].SectionGiven.Contains("Header") && list[i].BinId != 11)
                {
                    if (true)
                    {
                        Random rdHear = new Random();
                        int rdi = rdHear.Next(0x1500, 0x1600);
                        while (rdi % 4 != 0)
                        {
                            rdi = rdHear.Next(0x1500, 0x1600);
                        }
                        list[i].AddressNo = rdi.ToString("X4");

                    }
                    else
                    {
                        list[i].AddressNo = 0x1500.ToString("X4");
                    }

                }
                ////计算0x1000整倍数
                else if (list[i].BinId == 11 || list[i].BinId == 13 || list[i].BinId == 14 || list[i].BinId == 15)
                {
                    var Setting_flagAddressNo = ((Convert.ToUInt32(list[i - 1].Address, 16) + Convert.ToUInt32(list[i - 1].LengthAddress, 16)) / 4096 + 1) * 4096;
                    list[i].AddressNo = Setting_flagAddressNo.ToString("X4");
                }
                else
                {
                    if ((Convert.ToUInt32(list[i - 1].Address, 16) + Convert.ToUInt32(list[i - 1].LengthAddress, 16)) % 0x1000 == 0)
                    {
                        list[i].AddressNo = (Convert.ToUInt32(list[i - 1].Address, 16) + Convert.ToUInt32(list[i - 1].LengthAddress, 16) + 0x20).ToString("X4");
                    }
                    else
                    {
                        var Setting_flagAddressNo = ((Convert.ToUInt32(list[i - 1].Address, 16) + Convert.ToUInt32(list[i - 1].LengthAddress, 16)) / (32) + 1) * 32;
                        list[i].AddressNo = Setting_flagAddressNo.ToString("X4");
                    }
                }

                list[i].Address = (Convert.ToUInt32(list[i].AddressNo, 16)).ToString("X4");
                if (list[i].BinId == 10 && list[i].SerialNo == 1)
                {

                    UInt32 tempy = Convert.ToUInt32(list[i].AddressNo, 16) % 0x1000;
                    list[i].Address = (0x1000 - tempy + Convert.ToUInt32(list[i].AddressNo, 16)).ToString("X4");
                    list[i].AddressNo = list[i].Address;
                }
                Bincurrency_BLL.Update(list[i]);
            }
        }
        #endregion
        #region 刷新界面
        /// <summary>
        /// 刷新界面
        /// </summary>
        private void RefreshGridView()
        {
            context.Post(t =>
            {
                var aaa = Bincurrency_BLL.GetListToDefault(GuidNo).Where(c => c.IsModified == 1).OrderBy(c => c.BinId == 10 ? 0 : 1);
                if (aaa.Count() == 0)
                {
                    Setting0_0.Checked = false;
                }
                this.gridControl1.DataSource = aaa;
                this.gridView1.RefreshData();
                this.gridView1.Invalidate();

            }, "");
        }
        #endregion
        #region 显示消息
        /// <summary>
        /// 显示消息
        /// </summary>
        /// <param name="msg"></param>
        private void SetShowMsg(string msg)
        {
            this.Invoke((EventHandler)(delegate
            {
                if (memoEdit1.Text.Length > 5000)
                {
                    memoEdit1.Text = "";
                }
                //追加的形式添加到文本框末端，并滚动到最后。     
                this.memoEdit1.Text = string.Format("{0} \r\n  {1}", this.memoEdit1.Text, msg);
                this.memoEdit1.SelectionStart = memoEdit1.Text.Length;
                this.memoEdit1.ScrollToCaret();
            }));
        }
        #endregion
        public class IniFiles
        {
            public string inipath;

            //声明API函数

            [DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileInt(string section, string key, int nDefault, string filePath);
            /// <summary> 
            /// 构造方法 
            /// </summary> 
            /// <param name="INIPath">文件路径</param> 
            public IniFiles(string INIPath)
            {
                inipath = INIPath;
            }

            public IniFiles() { }

            /// <summary> 
            /// 写入INI文件 
            /// </summary> 
            /// <param name="Section">项目名称(如 [TypeName] )</param> 
            /// <param name="Key">键</param> 
            /// <param name="Value">值</param> 
            public void IniWriteString(string Section, string Key, string Value)
            {
                WritePrivateProfileString(Section, Key, Value, this.inipath);
            }
            /// <summary> 
            /// 读出INI文件 
            /// </summary> 
            /// <param name="Section">项目名称(如 [TypeName] )</param> 
            /// <param name="Key">键</param> 
            public string IniReadString(string Section, string Key)
            {
                StringBuilder temp = new StringBuilder(500);
                int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
                return temp.ToString();
            }
            /// <summary> 
            /// 验证文件是否存在 
            /// </summary> 
            /// <returns>布尔值</returns> 
            public bool ExistINIFile()
            {
                return File.Exists(inipath);
            }
            public int IniReadInt(string Section, string Key, int nDefault)
            {
                return GetPrivateProfileInt(Section, Key, nDefault, this.inipath);
            }
            public long IniWriteInt(string Section, string Key, int nValue)
            {
                string sValue = Convert.ToString(nValue);
                return WritePrivateProfileString(Section, Key, sValue, this.inipath);
            }
        }

        private void osdcheck_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                if (Setting0_0.Checked)
                {
                    Setting0_0.Checked = false;
                    Setting0_0.Checked = true;
                }
                //osdCZcheck.Enabled = false;
                bincurrency model = new bincurrency();
                model.BinId = 10;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 0;
                model.Reorder = 5;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                //osdCZcheck.Enabled = true;
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 10);
                //计算地址 
                //AutomaticAddress(GuidNo);
                //去除上一次的OSDTips
                SettingTo151_Help.setTips151clear();

            }
            //设置是否开启使能开关
            setDataexample(xcBaseList.Where(c => c.Id == 30).First().address, ischecked.Checked, ref xcBaseList);
            // 刷新界面
            RefreshGridView();
        }

        private void Setting0_0_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                bincurrency model = new bincurrency();
                //model.AddressNo = "1000";
                //model.Address = "2000";
                model.BinId = 6;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.FileStatus = 0;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                if (!osdcheck.Checked)
                {
                    SettingToTve151.ClearTve151();
                }  
                //
                //Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 116);
                //Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 116);
                //Setting勾选框未勾选时，需同时删除setting区数据
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && (c.BinId == 6 || c.BinId == 7 || c.BinId == 8 || c.BinId == 9));
                //计算地址 
                //AutomaticAddress(GuidNo);
                //Config_en.Checked = false;
            }

            //setDataexample(xcBaseList.Where(c => c.Id == 17).First().address, ischecked.Checked, ref xcBaseList);
            // 刷新界面

            RefreshGridView();
        }

        private void Setting0_Patch_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                bincurrency model = new bincurrency();
                model.BinId = 4;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 0;
                model.Reorder = 5;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 4);
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            //设置是否开启使能开关
            setDataexample(xcBaseList.Where(c => c.Id == 28).First().address, ischecked.Checked, ref xcBaseList);
            // 刷新界面
            RefreshGridView();
        }

        private void flashencryption_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                bincurrency model = new bincurrency();
                model.BinId = 12;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 0;
                model.Reorder = 5;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 12);
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            // 刷新界面
            RefreshGridView();
        }

        private void Code_en_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                bincurrency model = new bincurrency();
                model.BinId = 5;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 0;
                model.Reorder = 5;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 5);
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            //设置是否开启使能开关
            setDataexample(xcBaseList.Where(c => c.Id == 29).First().address, ischecked.Checked, ref xcBaseList);
            // 刷新界面
            RefreshGridView();
        }
        public string Copy_Files_For_Header_Patch_Tool(string Inputfilepath, bool Isflash, string eepromaddr, bool isSetting, bool isHead, uint setHex = 0x0)
        {
            string strFileName = System.IO.Path.GetFileName(Inputfilepath); //获取文件名
            string strNewSavePath = Application.StartupPath + "\\Lib\\xc151_setting\\Flash_" + setHex.ToString("X2") + strFileName;
            //判断该路径下文件是否存在
            if (File.Exists(strNewSavePath))
            {
                //如果存在文件就删除
                File.Delete(strNewSavePath);
            }
            if (isHead)
            {
                Setting2FlashE2prom.FlashHeader2Flash(Inputfilepath, strNewSavePath);
            }
            else
            {
                //Setting2FlashE2prom.FlashSetting2Flash(Inputfilepath, strNewSavePath, 1, 0, 0);
                Setting2FlashE2prom.FlashSetting2Flash(Inputfilepath, strNewSavePath, 0, 0, 0, 0, 0, setHex);
            }

            return strNewSavePath;
        }
        private void BinSetting(string pathName, string tag, uint hex = 0x0)
        {
            //setting0~setting47   common_setting setting48 setting49~setting98
            var list = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && (c.BinId == 6 || c.BinId == 7 || c.BinId == 8 || c.BinId == 9) && c.SerialNo != 48);
            var tagTemp = (int.Parse(tag) - 1);
            uint settingHex = hex; 
            if (list.Exists(c => c.SerialNo == tagTemp))
            {
                var model = list.Find(c => c.SerialNo == tagTemp);
                model.BinInPath = pathName;
                model.BinInName = Path.GetFileName(pathName);
                var pathNameout = Copy_Files_For_Header_Patch_Tool(pathName, true, "", true, false, settingHex);
                model.BinOutName = Path.GetFileName(pathNameout);
                model.BinOutPath = pathNameout;
                model.SerialNo = tagTemp;
                model.FileStatus = 2;
                model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                Bincurrency_BLL.Update(model);
            }
            else
            {
                bincurrency model = new bincurrency();
                model.GuidId = GuidNo;
                model.BinId = (tagTemp / 32) + 6;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                model.BinInPath = pathName;
                model.BinInName = Path.GetFileName(pathName);
                var pathNameout = Copy_Files_For_Header_Patch_Tool(pathName, true, "", true, false, settingHex);
                model.BinOutName = Path.GetFileName(pathNameout);
                model.BinOutPath = pathNameout;
                model.FileStatus = 2;
                model.SerialNo = tagTemp;
                //model.SortOrder = modelMax + 1;
                model.SortOrder = tagTemp;
                model.IsModified = 0;
                model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                Bincurrency_BLL.Insert(model);
            }
        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                //bNeedIni = Convert.ToBoolean(int.Parse(GetConfigValue("xcCreateBinNeedIni")));

                //if (bNeedIni && string.IsNullOrEmpty(IniPath.Text) && Setting0_0.Checked)
                //{
                //    //只有Patch文件做bin时，不需要ini
                //    XtraMessageBox.Show("ini不能为空，请先导入ini文件！");
                //    return;
                //}
                //setting寄存器添加寄存器至config0中
                //if (File.Exists(Application.StartupPath + "\\Lib\\xc151_setting\\XChipndndOSDSetting.txt"))
                //{
                //    var configlist = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 2);
                //    if (0 == configlist.Count())
                //    {
                //        bincurrency modelconfig = new bincurrency();
                //        modelconfig.GuidId = GuidNo;
                //        modelconfig.BinId = 2;
                //        modelconfig.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                //        modelconfig.BinInPath = Application.StartupPath + "\\Lib\\xc151_setting\\XChipLoadAndOSDSetting.txt";
                //        modelconfig.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\xc151_setting\\XChipLoadAndOSDSetting.txt");
                //        var pathNameout = Copy_Files_For_Config_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\XChipLoadAndOSDSetting.txt", true, "", true, false);
                //        modelconfig.BinOutName = Path.GetFileName(pathNameout);
                //        modelconfig.BinOutPath = pathNameout;
                //        modelconfig.FileStatus = 2;
                //        modelconfig.SerialNo = 0;
                //        modelconfig.SortOrder = 0;
                //        modelconfig.IsModified = 1;
                //        modelconfig.LengthAddress = HeaderHelper.FilePathLengthComplementnew(modelconfig.BinOutPath);
                //        Bincurrency_BLL.Insert(modelconfig);
                //    }
                //    else
                //    {

                //        //复制一份数据
                //        List<string> lines = new List<string>();

                //        using (StreamReader sr = new StreamReader(Application.StartupPath + "\\Lib\\xc151_setting\\XChipLoadAndOSDSetting.txt"))
                //        {
                //            while (sr.Peek() >= 0)
                //            {
                //                lines.Add(sr.ReadLine());
                //            }
                //        }
                //        var modelconfig = configlist.Find(c => c.GuidId == GuidNo && c.BinId == 2);
                //        File.Copy(modelconfig.BinInPath, Application.StartupPath + "\\Lib\\xc151_setting\\config0addsetting.txt");
                //        File.AppendAllLines(Application.StartupPath + "\\Lib\\xc151_setting\\config0addsetting.txt", lines);
                //        modelconfig.BinInPath = Application.StartupPath + "\\Lib\\xc151_setting\\config0addsetting.txt";
                //        modelconfig.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\xc151_setting\\config0addsetting.txt");
                //        var pathNameout = Copy_Files_For_Config_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\config0addsetting.txt", true, "", true, false);
                //        modelconfig.BinOutName = Path.GetFileName(pathNameout);
                //        modelconfig.BinOutPath = pathNameout;
                //        modelconfig.SerialNo = 0;
                //        modelconfig.FileStatus = 2;
                //        modelconfig.LengthAddress = HeaderHelper.FilePathLengthComplementnew(modelconfig.BinOutPath);
                //        Bincurrency_BLL.Update(modelconfig);
                //    }
                //}
                if (OsdVerCheck.Checked)
                {
                    //判断该路径下文件是否存在
                    if (!File.Exists(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_Setting.txt"))
                    {
                        XtraMessageBox.Show("请导入setting文件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    List<string> SoftwareLines = File.ReadAllLines(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_Setting.txt").ToList();
                    //判断该路径下文件是否存在
                    if (File.Exists(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_SettingAddOsdVer.txt"))
                    {
                        //如果存在文件就删除
                        File.Delete(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_SettingAddOsdVer.txt");
                    }
                    //ParaHelp.Osd_Version_Info
                    List<string> Osd_Versionlist = new List<string>();
                    foreach (var item in ParaHelp.Osd_Version_Info)
                    {
                        Osd_Versionlist.Add($"{ item.PKey},{item.PValue},{item.Note}");
                    }
                    //这里可以处理删除无需要的OSDVersion寄存器
                    SoftwareLines.AddRange(Osd_Versionlist);
                    File.AppendAllLines(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_SettingAddOsdVer.txt", SoftwareLines);
                    BinSetting(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_SettingAddOsdVer.txt", "128");


                }
                else
                {
                    if ((Config_en.Checked && !Setting0_0.Checked) || checkEdit1.Checked)
                    {

                    }
                    else
                    {
                        BinSetting(Application.StartupPath + "\\Lib\\xc151_setting\\XChipSoftware_Specific_Setting.txt", "128");
                    }
                }


                var aaatt =  Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.IsModified == 1 && c.FileStatus == 0).ToList();
                if (aaatt.Count()!=0)
                {
                    XtraMessageBox.Show("有文件未导入", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                                //list.Clear();
                //list = Bincurrency_BLL.GetListToDefault(GuidNo).ToList();
                //获取PID,VID
                string csPID = "", csVID = "";
                string csSetting1FullFile = "";

                ////输入框中有PID,VID则直接获取，否则从setting1中获取
                //if (strPID.Text.Length > 0 && strVID.Text.Length > 0)
                //{
                //    csPID = strPID.Text;
                //    csVID = strVID.Text;
                //} 
                //else
                //{
                //    var modelSetting1 = Bincurrency_BLL.GetSingle(c => c.GuidId == GuidNo && c.SerialNo == 0 && c.BinId == 118);
                //    if (modelSetting1 != null)
                //    {
                //        csSetting1FullFile = modelSetting1.BinInName;
                //        string strText = File.ReadAllText(csSetting1FullFile);

                //        csPID = objIni.GetRegValue("a5a", strText, 2).ToString("x4");
                //        csVID = objIni.GetRegValue("a58", strText, 2).ToString("x4");
                //    }
                //}
                //按南清的要求，bin生成目录默认成Setting文件夹目录
                string strPIDVID = "";
                if (!string.IsNullOrEmpty(csPID) && !string.IsNullOrEmpty(csVID))
                {
                    strPIDVID = string.Format("_P{0}_V{1}", csPID, csVID);
                }
                string strBinPath = "";
                if (ConfigurationManager.AppSettings.AllKeys.Contains("Folder_BinSetting") && GetConfigValue("Folder_BinSetting") != "")
                {
                    strBinPath = GetConfigValue("Folder_BinSetting");
                }
                else if (ConfigurationManager.AppSettings.AllKeys.Contains("Folder_Road_Force_Setting"))
                {
                    strBinPath = GetConfigValue("Folder_Road_Force_Setting");
                }
                else
                {
                    strBinPath = GetConfigValue("Folder_Road_Force");
                }
                 
                //string strBinName = Path.GetFileNameWithoutExtension(strBinPath);
                //string Save_BIN_Output_File_FileName_Path = strBinPath + "\\" + strBinName + strPIDVID +
                //    $"_{DateTime.Now.ToString("yyyyMMddHHmm")}" + ".bin";

                //string strBinName = Path.GetFileNameWithoutExtension(strBinPath);
                string strBinName = strBinPath.Substring(strBinPath.LastIndexOf('\\') + 1);
                string Save_BIN_Output_File_FileName_Path = strBinPath + "\\" + strBinName + strPIDVID +
                    $"_{DateTime.Now.ToString("yyyyMMddHHmm")}" + ".bin";

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "bin文件（*.bin）|*.bin";
                //设置默认文件类型显示顺序 
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录 
                sfd.RestoreDirectory = true;
                sfd.InitialDirectory = strBinPath;
                sfd.FileName = Path.GetFileName(Save_BIN_Output_File_FileName_Path);
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    //DirectoryInfo parentDirectory = Directory.GetParent(sfd.FileName);
                    //string parentDirectoryName = parentDirectory.Name;
                    ///sfd.FileName = Path.GetDirectoryName(sfd.FileName) + "\\" + parentDirectoryName + Path.GetFileName(sfd.FileName);
                    Save_BIN_Output_File_FileName_Path = sfd.FileName;

                    var selected2Value = comboBox2.SelectedIndex;
                    if (!isUSB.Checked)
                    {
                        //USBbin生成时需要去除
                        if (selected2Value <= 2 && !Setting0_Patch.Checked && Setting0_0.Checked)
                        {
                            Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 4);
                            bincurrency modelp = new bincurrency();
                            modelp.BinId = 4;
                            modelp.GuidId = GuidNo;
                            //model.IsModified = 1;
                            modelp.SerialNo = 0;
                            modelp.SortOrder = 0;
                            modelp.Reorder = 5;
                            modelp.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                            modelp.BinInPath = Application.StartupPath + "\\Lib\\Code_XC151_patch.bin";
                            modelp.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\Code_XC151_patch.bin");
                            var pathp = patch_Copy_Files_For_Header_Patch_Tool(Application.StartupPath + "\\Lib\\Code_XC151_patch.bin", true, "", true, false, (int)modelp.BinId);
                            modelp.BinOutName = System.IO.Path.GetFileName(pathp); //获取文件名
                            modelp.BinOutPath = pathp;
                            modelp.FileStatus = 2;
                            //文件长度
                            modelp.LengthAddress = FilePathLengthComplement(pathp);
                            Bincurrency_BLL.Insert(modelp);
                            //设置是否开启使能开关
                            setDataexample(xcBaseList.Where(c => c.Id == 28).First().address, true, ref xcBaseList);
                        }
                    }

                    //将加载Setting数据的模式写入config0中，如果没有就创建一个config0
                    if (Config_en.Checked)
                    {
                        List<string> configlist = new List<string>();
                        configlist.Add("0xfffd,0x20,");
                        configlist.Add("0xfffe,0x00,");
                        if (Fast_Read_en.Checked)
                        {
                            configlist.Add("0x14b3,0x01,");
                        }
                        else
                        {
                            configlist.Add("0x14b3,0x00,");
                        }
                        var config0is1 = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 2).ToList();
                        var modelx = config0is1.Find(c => c.GuidId == GuidNo && c.BinId == 2);
                        if (config0is1 != null && modelx.BinInPath != null)
                        {
                            List<string> existingLines = File.ReadAllLines(modelx.BinInPath).ToList();
                            existingLines.InsertRange(0, configlist);
                            //判断该路径下文件是否存在
                            if (File.Exists(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt"))
                            {
                                //如果存在文件就删除
                                File.Delete(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                            }
                            File.AppendAllLines(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", existingLines);
                            modelx.BinInPath = Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt";
                            modelx.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                            var pathNameout = config_Files_For_Header_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", true, "", true, false);
                            modelx.BinOutName = Path.GetFileName(pathNameout);
                            modelx.BinOutPath = pathNameout;
                            modelx.SerialNo = 0;
                            modelx.FileStatus = 2;
                            modelx.LengthAddress = HeaderHelper.FilePathLengthComplementnew(modelx.BinOutPath);
                            Bincurrency_BLL.Update(modelx);
                            //设置是否开启使能开关
                            setDataexample(xcBaseList.Where(c => c.Id == 26).First().address, true, ref xcBaseList);
                        }
                        else
                        {
                            //判断该路径下文件是否存在
                            if (File.Exists(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt"))
                            {
                                //如果存在文件就删除
                                File.Delete(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                            }
                            File.AppendAllLines(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", configlist);
                            bincurrency modelp = new bincurrency();
                            var listcongig = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 2);
                            if (listcongig.Count == 0)
                            {
                                modelp.BinId = 2;
                                modelp.GuidId = GuidNo;
                                //model.IsModified = 1;
                                modelp.SerialNo = 0;
                                modelp.SortOrder = 0;
                                modelp.Reorder = 5;
                                modelp.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                                modelp.BinInPath = Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt";
                                modelp.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                                var pathp = config_Files_For_Header_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", true, "", true, false);
                                modelp.BinOutName = System.IO.Path.GetFileName(pathp); //获取文件名
                                modelp.BinOutPath = pathp;
                                modelp.FileStatus = 2;
                                //文件长度
                                modelp.LengthAddress = FilePathLengthComplement(pathp);
                                Bincurrency_BLL.Insert(modelp);
                            }
                            else
                            {
                                var modely = listcongig.Find(c => c.GuidId == GuidNo && c.BinId == 2);
                                modely.BinInPath = Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt";
                                modely.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                                var pathNameout = config_Files_For_Header_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", true, "", true, false);
                                modely.BinOutName = Path.GetFileName(pathNameout);
                                modely.BinOutPath = pathNameout;
                                modely.SerialNo = 0;
                                modely.FileStatus = 2;
                                modely.Reorder = 5;
                                modely.LengthAddress = HeaderHelper.FilePathLengthComplementnew(modely.BinOutPath);
                                Bincurrency_BLL.Update(modely);
                            }
                            //设置是否开启使能开关
                            setDataexample(xcBaseList.Where(c => c.Id == 26).First().address, true, ref xcBaseList);
                        }
                    }
                    else
                    {
                        List<string> configlist = new List<string>();
                        configlist.Add("0xfffd,0x20,");
                        configlist.Add("0xfffe,0x00,");
                        if (Fast_Read_en.Checked)
                        {
                            configlist.Add("0x14b3,0x01,");
                        }
                        else
                        {
                            configlist.Add("0x14b3,0x00,");
                        }

                        //判断该路径下文件是否存在
                        if (File.Exists(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt"))
                        {
                            //如果存在文件就删除
                            File.Delete(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                        }
                        File.AppendAllLines(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", configlist);
                        bincurrency modelp = new bincurrency();
                        var listcongig = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 2);
                        if (listcongig.Count == 0)
                        {
                            modelp.BinId = 2;
                            modelp.GuidId = GuidNo;
                            //model.IsModified = 1;
                            modelp.SerialNo = 0;
                            modelp.SortOrder = 0;
                            modelp.Reorder = 5;
                            modelp.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                            modelp.BinInPath = Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt";
                            modelp.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                            var pathp = config_Files_For_Header_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", true, "", true, false);
                            modelp.BinOutName = System.IO.Path.GetFileName(pathp); //获取文件名
                            modelp.BinOutPath = pathp;
                            modelp.FileStatus = 2;
                            //文件长度
                            modelp.LengthAddress = FilePathLengthComplement(pathp);
                            Bincurrency_BLL.Insert(modelp);
                        }
                        else
                        {
                            var modelx = listcongig.Find(c => c.GuidId == GuidNo && c.BinId == 2);
                            modelx.BinInPath = Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt";
                            modelx.BinInName = Path.GetFileName(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt");
                            var pathNameout = config_Files_For_Header_Patch_Tool(Application.StartupPath + "\\Lib\\xc151_setting\\Config0AddSettingRead.txt", true, "", true, false);
                            modelx.BinOutName = Path.GetFileName(pathNameout);
                            modelx.BinOutPath = pathNameout;
                            modelx.SerialNo = 0;
                            modelx.FileStatus = 2;
                            modelx.Reorder = 5;
                            modelx.LengthAddress = HeaderHelper.FilePathLengthComplementnew(modelx.BinOutPath);
                            Bincurrency_BLL.Update(modelx);
                        }
                        //设置是否开启使能开关
                        setDataexample(xcBaseList.Where(c => c.Id == 26).First().address, true, ref xcBaseList);
                    }
                }
                else
                {
                    return;
                }
                AutomaticAddress(GuidNo);
                var list = Bincurrency_BLL.GetListToDefault(GuidNo).Where(c => !string.IsNullOrEmpty(c.Address) || !string.IsNullOrEmpty(c.LengthAddress)).OrderBy(c => c.BinId).ThenBy(c => c.SerialNo).ToList();
                //存储当前bin文件存放地址用于下一次生成
                AppHelper.UpdateAppConfig("Folder_Road_Force_Setting", Path.GetDirectoryName(sfd.FileName));
                //WaitBefore.Start("请耐心等待...", "正在努力生成bin文件中");
                SetShowMsg($"开始头文件生成！");
                string xc151head = string.Format("{0}\\Lib\\xc{1}_header\\{2}", Application.StartupPath, ConfigurationManager.AppSettings["xcVersion"], ConfigurationManager.AppSettings["xc151_header"]);
                string pSavePath = System.IO.Path.GetDirectoryName(xc151head); //获取文件路径
                string patchSavePath = pSavePath + "\\151_Header_Inputfile.txt";
                string strPU_PatchPath = string.Format("{0}\\PU_Patch.txt", pSavePath);
                //var maxAddr = list.Max(c => Convert.ToUInt32(c.Address, 16)).ToString("X4");
                //var maxData = list.Find(c => c.Address == maxAddr);
                //var noAddress = (Convert.ToUInt32(maxData.Address, 16) + Convert.ToUInt32(maxData.LengthAddress, 16)+0x1000).ToString("X4");
                if (File.Exists(strPU_PatchPath))
                {
                    File.Delete(strPU_PatchPath);
                }
                EnableAreaReassignment(list);
                //var lastset3 = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 9).OrderBy(c => c.BinId).ToList().FindLast(c => c.BinId == 9);
                //var list11 = Bincurrency_BLL.GetListToDefault(GuidNo).Where(c => c.BinId != 116).OrderBy(c => c.BinId).ToList();
                //int count = list11.Count();
                //int i = 1;
                var binsizelist = list.OrderByDescending(c => Convert.ToUInt32(c.Address, 16)).FirstOrDefault();
                var binsize = (Convert.ToInt32(binsizelist.Address, 16) + Convert.ToInt32(binsizelist.LengthAddress, 16)).ToString("X");
                SetAddressLength("binsize", binsize, binsize, binsize, ref xcBaseList, true, 0);
                var osdList = list.Where(c => c.BinId == 10).ToList();
                var osdModel = osdList.Find(c => c.SerialNo == 0);
                if (osdList.Count > 1)
                {
                    SetAddressLength("OSD_Menu", osdModel.AddressNo, osdModel.Address, osdModel.LengthAddress, ref xcBaseList, true, (int)osdModel.SerialNo);
                    var osdAddr = (Convert.ToUInt32(osdModel.Address, 16) + Convert.ToUInt32(osdModel.BinAddressNo, 16) * (int)osdModel.Reorder).ToString("X4");
                    SetAddressLength("OSD_Font", osdAddr, osdAddr, osdModel.BinAddressOutName, ref xcBaseList, true, (int)osdModel.SerialNo);
                    osdModel = osdList.Find(c => c.SerialNo == 1);
                    SetAddressLength("OSD_save_exit", osdModel.AddressNo, osdModel.Address, osdModel.LengthAddress, ref xcBaseList, true, (int)osdModel.SerialNo);
                    osdModel = osdList.Find(c => c.SerialNo == 2);
                    SetAddressLength("OSD_reset", osdModel.AddressNo, osdModel.Address, osdModel.LengthAddress, ref xcBaseList, true, (int)osdModel.SerialNo);
                }
                else if (osdList.Count == 1)
                {
                    SetAddressLength("OSD_Font", osdModel.AddressNo, osdModel.Address, osdModel.LengthAddress, ref xcBaseList, true, (int)osdModel.SerialNo);
                }
                if (!PUCT_en.Checked)
                {
                    SetAddressLength("PUCT", "FFFFFFFF", "FFFFFFFF", "FFFFFFFF", ref xcBaseList, true, 0);
                }
                foreach (var item in list)
                {
                    if (item.BinId == 10)
                    {
                        continue;
                    }
                    else
                    {
                        SetAddressLength(item.SectionGiven, item.AddressNo, item.Address, item.LengthAddress, ref xcBaseList, true, (int)item.SerialNo);
                    }
                    if (flashencryption.Checked && item.BinId == 12)
                    {
                        SetAddressLength(item.SectionGiven, item.AddressNo, item.Address, item.LengthAddress, ref xcBaseList, true, (int)item.SerialNo);

                    }
                    //var addresNo = item.AddressNo;
                    //if (item.BinId != 10 && item.BinAddressOutName == null)
                    //{
                    //    SetAddressLength(item.SectionGiven, addresNo, item.Address, item.LengthAddress, ref xcBaseList, true, (int)item.SerialNo);
                    //}
                    ////暂时这样子写后期要改，SettingFalg添加
                    //if (item.BinAddressOutName != null && item.BinAddressNo != null)
                    //{
                    //    List<bincurrency_export> listset = new List<bincurrency_export>();
                    //    listset.AddRange(list);
                    //    listset.RemoveAll(c => c.BinInPath == null && c.BinId != 1);
                    //    var FlagLength = listset.Sum(c => Convert.ToUInt32(c.LengthAddress, 16)) + 0x1000;
                    //    SetAddressLength(item.SectionGiven, addresNo, item.Address, FlagLength.ToString("X4"), ref xcBaseList, true, 1);
                    //}
                    //if (item.BinId == 10)
                    //{
                    //    string strFlash = "OSD_Flash";
                    //    string strFont = "OSD_Font";
                    //    string strM = "OSD_Menu";
                    //    string strOutFlash = "OSD_ResetData";
                    //    if (item.BinInName.Contains(strFlash))
                    //    {
                    //        SetAddressLength(strFlash, addresNo, item.Address, item.LengthAddress, ref xcBaseList, true, (int)item.SerialNo);
                    //    }
                    //    if (item.BinInName.Contains(strFont))
                    //    {
                    //        SetAddressLength(strFont, addresNo, item.Address, item.LengthAddress, ref xcBaseList, true, (int)item.SerialNo);
                    //    }
                    //    if (item.BinInName.Contains(strM))
                    //    {
                    //        SetAddressLength(strM, addresNo, item.Address, item.LengthAddress, ref xcBaseList, true, (int)item.SerialNo);
                    //    }
                    //    if (item.BinInName.Contains(strOutFlash))
                    //    {
                    //        SetAddressLength(strOutFlash, addresNo, item.Address, item.LengthAddress, ref xcBaseList, true, (int)item.SerialNo);
                    //    }

                    //}


                    //++i;
                }
                var txbox = GenerateHeaderFile(xcBaseList);
                SavePatchText(patchSavePath, txbox);
                var path = Copy_Files_For_Header_Patch_Tool(patchSavePath, true, "00", false, true);


                path = HeaderTokey(patchSavePath, path);


                //获取BinId = 1 的bincurrency_enxtend
                var model = list.Where(c => c.BinId == 1).First();
                model.BinInName = System.IO.Path.GetFileName(patchSavePath);
                model.BinInPath = patchSavePath;
                model.BinOutName = System.IO.Path.GetFileName(path);
                model.BinOutPath = path;
                Bincurrency_BLL.Update(model);
                SetShowMsg($"开始头文件完毕！保存路径：{path}");

                string pXchip_Name = System.IO.Path.GetFileNameWithoutExtension(Save_BIN_Output_File_FileName_Path); //获取文件名
                string xcbin = string.Format("{0}\\Lib\\XChip_Bin\\{1}", Application.StartupPath, ConfigurationManager.AppSettings["XChip_Bin"]);

                SetShowMsg($"bin文件生成--->>>>>>>>>开始");

                //生成bin文件文本框
                StringBuilder sb = new StringBuilder();
                list = Bincurrency_BLL.GetListToDefault(GuidNo).Where(c => !string.IsNullOrEmpty(c.Address) || !string.IsNullOrEmpty(c.LengthAddress)).OrderBy(c => c.BinId).ThenBy(c => c.SerialNo).ToList();
                pSavePath = System.IO.Path.GetDirectoryName(xcbin); //获取文件路径

                var strIQpath = string.Format("{0}\\IQ.txt", pSavePath);


                var serlist = Serialdata_BLL.GetList();
                for (int j = 0; j < serlist.Count; j++)
                {
                    var strpaths = string.Format("{0}\\{1}.txt", pSavePath, j.ToString("X2"));
                    var iarr = serlist[j].FlashValue.Split(new char[1] { ',' });
                    List<string> aaa = HexStringToStringList(iarr[0]);
                    iarr[0] = aaa[0] + aaa[4] + aaa[3] + aaa[2] + aaa[1]+",";
                    aaa = HexStringToStringList(iarr[1]);
                    iarr[1] = aaa[0] + aaa[4] + aaa[3] + aaa[2] + aaa[1];
                    List<string> settingflaglist = new List<string>();
                    settingflaglist.AddRange(iarr);
                    settingflaglist.Add("0x4D4F4445,");
                    settingflaglist.Add("0x00000001,");
                    if (DCBL_en.Checked)
                    {
                        settingflaglist.AddRange(DCBLlist);
                    }
                    System.IO.File.WriteAllLines(strpaths, settingflaglist);
                    //GenerateFileHelp.StreamFileCreateText(strpaths, serlist[j].FlashValue);
                }


                List<FlashSettingModel> fsmList = new List<FlashSettingModel>();
                //int icount = 1;
                ////根据SerialNo排序找出第一个大于48的数据
                //var aaazzz =  list.OrderBy(z=>z.SerialNo).ToList().Find(c=>c.SerialNo > 48);
                ////获取第一个大于48的数据在list中的索引
                //var SerialNolist = list.FindIndex(c => c == aaazzz);
                ////在指定索引插入数据listaaaa
                //list.Insert(SerialNolist, listaaaa);
                for (int i = 0; i < list.Count(); i++)
                {
                    if (!string.IsNullOrEmpty(list[i].BinOutPath))
                    {
                        if (list[i].SectionGiven.Contains("Header"))
                        {
                            var length = list.Where(c => c.BinId != 1).Min(c => Convert.ToUInt32(c.AddressNo,16));
                            fsmList.Add(new FlashSettingModel()
                            {
                                fileAddr = list[i].Address,
                                fileLength = length.ToString("X4"),
                                fileName = list[i].BinOutPath,
                            });
                        }
                        else
                        {
                            fsmList.Add(new FlashSettingModel()
                            {
                                fileAddr = list[i].Address,
                                fileLength = list[i].LengthAddress,
                                fileName = list[i].BinOutPath,
                            });
                        }

                    }
                }
                //添加编号地址
                //FlashSettingModel famodel = new FlashSettingModel();
                //famodel.fileAddr = noAddress;
                //famodel.fileLength = "0x1000";
                //var model112 = list.Find(c => c.BinId == 11 && c.SortOrder == 0);
                //if (model112 != null)
                //{
                //    if (string.IsNullOrEmpty(model112.BinAddressNo))
                //    {   //如果没有选择编号  就采用第一套的编号为地址
                //        famodel.fileName = $"{list.First(c => c.BinId == 11 && !string.IsNullOrEmpty(c.BinOutName)).SerialNo}.txt";
                //    }
                //    else
                //    {
                //        famodel.fileName = model112.BinAddressOutName;
                //    }

                //    fsmList.Add(famodel);
                //}

                Setting2FlashE2prom.FlashSetting2Bin(Save_BIN_Output_File_FileName_Path, fsmList, 1, false,pXchip_Name);

                SetShowMsg($"bin保存文件：{Save_BIN_Output_File_FileName_Path}");

                //if (!string.IsNullOrEmpty(IniPath.Text))
                //{
                //    OLocalIni = new IniFiles(IniPath.Text);
                //    OLocalIni.IniWriteInt("Enable", "Patch", Convert.ToInt32(Patch0.Checked));
                //    OLocalIni.IniWriteInt("Enable", "Parameter", Convert.ToInt32(Patch2.Checked));
                //}

                //WaitBefore.Close();
                var showDev = XtraMessageBox.Show("生成成功！文件路径：" + Save_BIN_Output_File_FileName_Path, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                xcBaseList = JsonConvert.DeserializeObject<List<xc151>> (xc151_exBll.GetListToXc151()); 
                SetShowMsg($"bin文件生成<<<<<<<<<<---结束");
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        string HeaderTokey(string pSavePath, string path)
        {
            uint headerKey = 0x368; //头文件存放地址
            uint headerLength = 0x320; //头文件生成长度228行固定 带crc
            //随机范围
            uint headerMax = 0x1500 - headerLength;
            Random rdHear = new Random();
            //由于AB分区有扩张所以不能从368+8开始，需要往后推随机范围，不然会占用
            //改为从0x1000开始
            int rdi = rdHear.Next(0x1000, (int)headerMax);
            while (rdi % 4 != 0)
            {
                rdi = rdHear.Next(0x1000, (int)headerMax);
            }
            var IsRandomaddr = ConfigurationManager.AppSettings["IsRandomaddr"];
            if (IsRandomaddr != "")
            {
                rdi = Convert.ToInt32(IsRandomaddr, 16);
            }
            var IsRandom = ConfigurationManager.AppSettings["IsRandom"] == "0";
            if (IsRandom)
            {
                rdi = 0;
            }
            StringBuilder sb = new StringBuilder();
            if (rdi == 0)
            {
                sb.Append(File.ReadAllText(path));
            }
            else
            {
                var headerList = File.ReadAllLines(path);
                var headerNo = Math.Ceiling(headerList.Count() * 0.2);
                for (int j = 0; j < headerNo; j += 4)
                {
                    sb.Append($"{headerList[j]}\n");

                }
                for (int i = 0; i < headerKey - headerNo; i += 4)
                {

                    if (IsRandom)
                    {
                        var hig1 = (Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255))) << 24);
                        var hig2 = (Convert.ToUInt32(Convert.ToByte(0)) << 16);
                        var low1 = (Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255))) << 8);
                        var low2 = Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255)));
                        long temp = hig1 + hig2 + low1 + low2;
                        sb.Append($"0x{Convert.ToUInt32(temp).ToString("X8")},\n");
                    }
                    else
                    {
                        sb.Append($"0x00000000,\n");
                    }
                }
                //如果没有偏移需要跳过该条赋值不然会多加一条数据进去
                sb.Append($"0x{(rdi & 0xff).ToString("X2")}{(rdi >> 8 & 0xff).ToString("X2")}0000,\n");
                for (int i = 4; i < (rdi - headerKey); i += 4)
                {

                    if (IsRandom)
                    {
                        var hig1 = (Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255))) << 24);
                        var hig2 = (Convert.ToUInt32(Convert.ToByte(0)) << 16);
                        var low1 = (Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255))) << 8);
                        var low2 = Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255)));
                        long temp = hig1 + hig2 + low1 + low2;
                        sb.Append($"0x{Convert.ToUInt32(temp).ToString("X8")},\n");
                    }
                    else
                    {
                        sb.Append($"0x00000000,\n");
                    }
                }

                sb.Append(File.ReadAllText(path));

            }
            for (uint i = Convert.ToUInt32(rdi) + headerLength; i < 0x1000; i += 4)
            {
                if (!IsRandom)
                {
                    var hig1 = (Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255))) << 24);
                    var hig2 = (Convert.ToUInt32(Convert.ToByte(0)) << 16);
                    var low1 = (Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255))) << 8);
                    var low2 = Convert.ToUInt32(Convert.ToByte(rdHear.Next(0, 255)));
                    long temp = hig1 + hig2 + low1 + low2;
                    sb.Append($"0x{Convert.ToUInt32(temp).ToString("X8")},\n");
                }
                else
                {
                    sb.Append($"0x00000000,\n");
                }

            }
            path = System.IO.Path.GetDirectoryName(pSavePath) + "\\Flash_H_" + Path.GetFileNameWithoutExtension(pSavePath) + ".txt";
            File.WriteAllText(path, sb.ToString());
            return path;
        }

        void EnableAreaReassignment(List<bincurrency_export> list)
        {
            //设置setting0-3区的使能开关


            //config0
            bool bEnable = list.Exists(c => c.BinId == 2);
            setDataexample(xcBaseList.Where(c => c.Id == 26).First().address, bEnable, ref xcBaseList);
            //config1
            bEnable = list.Exists(c => c.BinId == 3);
            setDataexample(xcBaseList.Where(c => c.Id == 27).First().address, bEnable, ref xcBaseList);

            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].BinId == 6 || list[i].BinId == 7 || list[i].BinId == 8 || list[i].BinId == 9)//Setting0
                {
                    setDataexample(xcBaseList.Where(c => c.Id == (37 + list[i].SerialNo)).First().address, true, ref xcBaseList);
                }
            }



            //            //Patch区与当前参数区默认打开使能，需根据是否勾选来赋值
            if (comboBox2.SelectedIndex <= 2 && !Setting0_Patch.Checked)
            {

            }
            else
            {
                setDataexample(xcBaseList.Where(c => c.Id == 28).First().address, Setting0_Patch.Checked, ref xcBaseList);
            }

            string selectedValue = (string)comboBox1.SelectedItem;
            switch (selectedValue)
            {
                //设置芯片应用场景
                case "ISP":
                    SetXcBase(xcBaseList.Where(c => c.Id == 12).ToList()[0].address, "00", ref xcBaseList);
                    break;
                case "ISP+TVE出图":
                    SetXcBase(xcBaseList.Where(c => c.Id == 12).ToList()[0].address, "01", ref xcBaseList);
                    break;
                case "仅桥接":
                    SetXcBase(xcBaseList.Where(c => c.Id == 12).ToList()[0].address, "02", ref xcBaseList);
                    break;
                case "ISP+USB出图":
                    SetXcBase(xcBaseList.Where(c => c.Id == 12).ToList()[0].address, "04", ref xcBaseList);
                    break;
                default:
                    break;
            }
            string selected2Value = (string)comboBox2.SelectedItem;
            switch (selected2Value)
            {
                //设置芯片应用场景
                case "编号优先":
                    SetXcBase(xcBaseList.Where(c => c.Id == 31).ToList()[0].address, "00", ref xcBaseList);
                    break;
                case "单GPIO优先":
                    SetXcBase(xcBaseList.Where(c => c.Id == 31).ToList()[0].address, "01", ref xcBaseList);
                    break;
                case "ADC&双GPIO轮询优先":
                    SetXcBase(xcBaseList.Where(c => c.Id == 31).ToList()[0].address, "02", ref xcBaseList);
                    break;
                case "编号优先非补丁":
                    SetXcBase(xcBaseList.Where(c => c.Id == 31).ToList()[0].address, "03", ref xcBaseList);
                    break;
                default:
                    break;
            }
            if (flashencryption.Checked) //Flash加密区
            {
                ////打开使能开关
                //SetXcBase(xcBaseList.Where(c => c.Id == 9).ToList()[0].address, "01", ref xcBaseList);
                ////设置加密模式
                //SetXcBase(xcBaseList.Where(c => c.Id == 11).ToList()[0].address, lstCryptType[0].ToString("x2"), ref xcBaseList);
                ////setDataexample(xcBaseList.Where(c => c.Id == 7).First().address, FlashCrypt.Checked, ref xcBaseList);
                //打开使能开关
                SetXcBase(xcBaseList.Where(c => c.Id == 9).ToList()[0].address, "01", ref xcBaseList);
                //设置加密模式
                var radio2Num = radioGroup2.Properties.Items[radioGroup2.SelectedIndex].Value;
                SetXcBase(xcBaseList.Where(c => c.Id == 11).ToList()[0].address, radio2Num.ToString().PadLeft(2, '0'), ref xcBaseList);
            }
            if (pollingcheck.Checked) 
            {
                //设置加密模式
                var radio2Num = radioGroup1.Properties.Items[radioGroup1.SelectedIndex].Value;
                SetXcBase(xcBaseList.Where(c => c.Id == 31).ToList()[0].address, radio2Num.ToString().PadLeft(2, '0'), ref xcBaseList);
            }
            if (Fast_Read_en.Checked)
            {
                //打开使能开关
                SetXcBase(xcBaseList.Where(c => c.Id == 7).ToList()[0].address, "01", ref xcBaseList);
            }
            else
            {
                //打开使能开关
                SetXcBase(xcBaseList.Where(c => c.Id == 7).ToList()[0].address, "00", ref xcBaseList);
            }
            if (osdcheck.Checked)//OSD区
            {
                if (osdCZcheck.Checked)
                {
                    SetXcBase(xcBaseList.Where(c => c.Id == 30).ToList()[0].address, "02", ref xcBaseList);
                }
                else
                {
                    SetXcBase(xcBaseList.Where(c => c.Id == 30).ToList()[0].address, "01", ref xcBaseList);
                }
                //更新菜单结构体的长度 和 字体长度
                List<string> menuList = HexStringToStringList(MenuLength.ToString("X4"));
                List<string> fontList = HexStringToStringList(FontLength.ToString("X4"));
                SetXcBase(xcBaseList.Where(c => c.Id == 740).ToList()[0].address, fontList[0], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 739).ToList()[0].address, fontList[1], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 738).ToList()[0].address, fontList[2], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 737).ToList()[0].address, fontList[3], ref xcBaseList);

                SetXcBase(xcBaseList.Where(c => c.Id == 732).ToList()[0].address, menuList[0], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 731).ToList()[0].address, menuList[1], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 730).ToList()[0].address, menuList[2], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 729).ToList()[0].address, menuList[3], ref xcBaseList);
            }
            if (Code_en.Checked)
            {
                SetXcBase(xcBaseList.Where(c => c.Id == 29).First().address, "01", ref xcBaseList);
            }

            //动态倒车线使能开关
            if (DCBL_en.Checked)
            {
                var DCBLlist = list.Where(c => c.BinId == 14).ToList();
                string input = "00000000";
                StringBuilder stringBuilder = new StringBuilder(input);
                for (int i = 0; i < DCBLlist.Count; i++)
                {
                    stringBuilder[input.Length - (int)DCBLlist[i].SerialNo - 1] = '1';
                }
                int decimalValue = Convert.ToInt32(stringBuilder.ToString(), 2);
                string hexValue = decimalValue.ToString("X");
                SetXcBase(xcBaseList.Where(c => c.Id == 32).First().address, hexValue, ref xcBaseList);
            }
            if (Log_en.Checked)
            {
                SetXcBase(xcBaseList.Where(c => c.Id == 33).First().address, "01", ref xcBaseList);
            }
            if (secretkeyEN.Checked)
            {
                var str = AppHelper.GetAppConfig("BinSecretKey");
                var blist = SettingList_Help.HexStringToStringList(AppHelper.XorNotEncryption(str).ToString("x4"));
                SetXcBase(xcBaseList.Where(c => c.Id == 21).First().address, blist[0], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 22).First().address, blist[1], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 23).First().address, blist[2], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 24).First().address, blist[3], ref xcBaseList);
                SetXcBase(xcBaseList.Where(c => c.Id == 25).First().address, "01", ref xcBaseList);
            }
            //读取配置文件设置使能开关;
            //SetIniModel();

        }
        public void SetXcBase(string _address, string _dataexample, ref List<xc151> XcBaseList)
        {
            XcBaseList.ForEach(c =>
            {
                if (c.address == _address)
                {
                    c.dataexample = string.Format("0x{0}", _dataexample);
                    return;
                }
            });
        }
        //设置头区可配置使能开关
        //public void SetIniModel()
        //{
        //    FileStream fs = new FileStream(strIniFileTxt, FileMode.Open, FileAccess.Read);
        //    StreamReader sr = new StreamReader(fs);
        //    //使用StreamReader类来读取文件 
        //    sr.BaseStream.Seek(0, SeekOrigin.Begin);
        //    // 从数据流中读取每一行，直到文件的最后一行
        //    string tmp = sr.ReadLine();
        //    while (tmp != null)
        //    {
        //        List<string> list11 = new List<string>(tmp.Split(':'));

        //        if (list11[0] == "CRC")
        //        {
        //            if (list11[1] == "0x00")
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 5).ToList()[0].address, "00", ref xcBaseList);
        //            }
        //            else
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 5).ToList()[0].address, "01", ref xcBaseList);
        //            }
        //        }

        //        if (list11[0] == "E2PROM")
        //        {
        //            if (list11[1] == "0x00")
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 6).ToList()[0].address, "00", ref xcBaseList);
        //            }
        //            else
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 6).ToList()[0].address, "01", ref xcBaseList);
        //            }
        //        }

        //        if (list11[0] == "SettingMode")
        //        {
        //            if (list11[1] == "0x00")
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 7).ToList()[0].address, "00", ref xcBaseList);
        //            }
        //            else
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 7).ToList()[0].address, "01", ref xcBaseList);
        //            }
        //        }

        //        if (list11[0] == "OSDModel")
        //        {
        //            if (list11[1] == "0x00")
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 8).ToList()[0].address, "00", ref xcBaseList);
        //            }
        //            else
        //            {
        //                SetXcBase(xcBaseList.Where(c => c.Id == 8).ToList()[0].address, "01", ref xcBaseList);
        //            }
        //        }


        //        list11.Clear();
        //        tmp = sr.ReadLine();
        //    }
        //    //关闭此StreamReader对象 
        //    sr.Close();
        //    fs.Close();
        //}
        /// <summary>
        /// 更新头文件地址
        /// </summary>
        /// <param name="showName"></param>
        /// <param name="serialno"></param>
        /// <param name="headaddress"></param>
        /// <param name="longitude"></param>
        /// <param name="XcBaseList"></param>
        /// <param name="flag"></param>
        public void SetAddressLength(string showName, string serialno, string headaddress, string longitude, ref List<xc151> XcBaseList, bool flag, int sernumber)
        {
            //使用配置的编号的地址    addresNo
            List<string> listNumber = HexStringToStringList(serialno);
            //第0套配置的首地址   item.Address
            List<string> listFirst = HexStringToStringList(headaddress);
            //每套配置的长度  item.LengthAddress
            List<string> listlength = HexStringToStringList(longitude);
            switch (showName)
            {
                case "boot_config_0":
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 168).ToList()[0].address, listNumber[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 167).ToList()[0].address, listNumber[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 166).ToList()[0].address, listNumber[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 165).ToList()[0].address, listNumber[3], ref XcBaseList);
                    }
                    break;
                case "boot_config_1":
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 172).ToList()[0].address, listNumber[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 171).ToList()[0].address, listNumber[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 170).ToList()[0].address, listNumber[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 169).ToList()[0].address, listNumber[3], ref XcBaseList);
                    }
                    break;
                case "Setting0"://setting0区配置0
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 216 + sernumber * 4).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 215 + sernumber * 4).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 214 + sernumber * 4).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 213 + sernumber * 4).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "Setting1"://setting1区配置1
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 216 + sernumber * 4).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 215 + sernumber * 4).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 214 + sernumber * 4).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 213 + sernumber * 4).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "Setting2"://setting2区配置2
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 216 + sernumber * 4).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 215 + sernumber * 4).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 214 + sernumber * 4).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 213 + sernumber * 4).ToList()[0].address, listFirst[3], ref XcBaseList);

                    }
                    break;
                case "Setting3"://setting3区配置3
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 216 + sernumber * 4).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 215 + sernumber * 4).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 214 + sernumber * 4).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 213 + sernumber * 4).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "boot_patch":
                    {
                        //起始地址
                        SetXcBase(XcBaseList.Where(c => c.Id == 176).ToList()[0].address, listNumber[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 175).ToList()[0].address, listNumber[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 174).ToList()[0].address, listNumber[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 173).ToList()[0].address, listNumber[3], ref XcBaseList);
                        //版本;
                        SetXcBase(XcBaseList.Where(c => c.Id == 180).ToList()[0].address, patchheader[8], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 179).ToList()[0].address, patchheader[9], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 178).ToList()[0].address, patchheader[10], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 177).ToList()[0].address, patchheader[11], ref XcBaseList);
                        //RAM地址;
                        SetXcBase(XcBaseList.Where(c => c.Id == 192).ToList()[0].address, patchheader[12], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 191).ToList()[0].address, patchheader[13], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 190).ToList()[0].address, patchheader[14], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 189).ToList()[0].address, patchheader[15], ref XcBaseList);
                        //patch入口;
                        SetXcBase(XcBaseList.Where(c => c.Id == 188).ToList()[0].address, patchheader[4], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 187).ToList()[0].address, patchheader[5], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 186).ToList()[0].address, patchheader[6], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 185).ToList()[0].address, patchheader[7], ref XcBaseList);
                        //patch长度;
                        SetXcBase(XcBaseList.Where(c => c.Id == 184).ToList()[0].address, patchheader[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 183).ToList()[0].address, patchheader[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 182).ToList()[0].address, patchheader[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 181).ToList()[0].address, patchheader[3], ref XcBaseList);
                    }
                    break;
                case "app_code":
                    {
                        //首地址
                        SetXcBase(XcBaseList.Where(c => c.Id == 196).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 195).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 194).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 193).ToList()[0].address, listFirst[3], ref XcBaseList);
                        //RAM写入地址;
                        SetXcBase(XcBaseList.Where(c => c.Id == 200).ToList()[0].address, codeheader[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 199).ToList()[0].address, codeheader[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 198).ToList()[0].address, codeheader[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 197).ToList()[0].address, codeheader[3], ref XcBaseList);
                        //长度;
                        SetXcBase(XcBaseList.Where(c => c.Id == 204).ToList()[0].address, codeheader[4], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 203).ToList()[0].address, codeheader[5], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 202).ToList()[0].address, codeheader[6], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 201).ToList()[0].address, codeheader[7], ref XcBaseList);
                        //版本信息;
                        SetXcBase(XcBaseList.Where(c => c.Id == 208).ToList()[0].address, codeheader[8], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 207).ToList()[0].address, codeheader[9], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 206).ToList()[0].address, codeheader[10], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 205).ToList()[0].address, codeheader[11], ref XcBaseList);
                        //入口地址
                        SetXcBase(XcBaseList.Where(c => c.Id == 212).ToList()[0].address, codeheader[12], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 211).ToList()[0].address, codeheader[13], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 210).ToList()[0].address, codeheader[14], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 209).ToList()[0].address, codeheader[15], ref XcBaseList);

                    }
                    break;
                case "FlashCryptKey":
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 16).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 15).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 14).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 13).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "OSD_save_exit"://OSD区配置
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 744).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 743).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 742).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 741).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "OSD_reset"://OSD区配置
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 748).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 747).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 746).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 745).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "OSD_Font"://OSD区配置
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 736).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 735).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 734).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 733).ToList()[0].address, listFirst[3], ref XcBaseList);

                    }
                    break;
                case "OSD_Menu"://OSD区配置
                    {

                        SetXcBase(XcBaseList.Where(c => c.Id == 728).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 727).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 726).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 725).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "OSD_siez"://OSD区配置
                    {

                        SetXcBase(XcBaseList.Where(c => c.Id == 728).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 727).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 726).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 725).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                //存放解密密码地址
                case "Key"://解密密码地址
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 16).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 15).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 14).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 13).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "Setting_Flag"://Setting_Flag
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 752).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 751).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 750).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 749).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "PUCT"://PUCT
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 756).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 755).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 754).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 753).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "DCBL"://动态倒车线0-8
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 760 + sernumber * 4).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 759 + sernumber * 4).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 758 + sernumber * 4).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 757 + sernumber * 4).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "boot_Log"://boot_Log
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 792).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 791).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 790).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 789).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                case "binsize"://binsize
                    {
                        SetXcBase(XcBaseList.Where(c => c.Id == 796).ToList()[0].address, listFirst[0], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 795).ToList()[0].address, listFirst[1], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 794).ToList()[0].address, listFirst[2], ref XcBaseList);
                        SetXcBase(XcBaseList.Where(c => c.Id == 793).ToList()[0].address, listFirst[3], ref XcBaseList);
                    }
                    break;
                default:
                    break;
            }
        }
        public List<string> HexStringToStringList(string str)
        {
            List<string> strlist = new List<string>();
            // //String.PadLeft(8,'0'); 表示检查字符串长度是否少于8位，若少于5位，则自动在其左侧以'0'补足。
            var str8 = str.PadLeft(8, '0');
            for (int i = 0; i < str8.Length; i += 2)
            {
                strlist.Add(str8.Substring(i, 2));
            }
            return strlist;
        }
        /// <summary>
        /// 根据list集合生成对应文件脚本
        /// </summary>
        /// <param name="XcBaseList"></param>
        /// <returns></returns>
        public string GenerateHeaderFile(List<xc151> XcBaseList)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in XcBaseList)
            {

                sb.Append(item.address + "," + item.dataexample + ",");
                sb.Append("\r\n");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 更具文件路径和内容生成文件
        /// </summary>
        /// <param name="Patch_FileName_Path"></param>
        /// <param name="contentTxt"></param>
        public void SavePatchText(string Patch_FileName_Path, string contentTxt)
        {
            using (StreamWriter sw = File.CreateText(Patch_FileName_Path))
            {
                sw.WriteLine(contentTxt);
                sw.Flush();
                sw.Close();
            }
        }
        public static void StreamFileCreateText(string fileName, string content)
        {
            using (StreamWriter sw = File.CreateText(fileName))
            {
                sw.WriteLine(content);
                sw.Flush();
                sw.Close();
            }
        }
        public void hideEvents(bool isbool = false)
        {
            Config_en.Visible = isbool;
            comboBox1.Visible = isbool;
            comboBox2.Visible = isbool;
            panelControl5.Visible = isbool;
            isUSB.Visible = isbool;
            Log_btn.Visible = isbool;
            PUCT_en.Visible = isbool;
            checkEdit1.Visible = isbool;
        }
        private void XChip_ToBin_Security_Load(object sender, EventArgs e)
        {
            if (isSecurity)
            {
                osdcheck.Visible = true;
                osd_panel.Visible = true;
                osdCZcheck.Visible = false;
                PUCT_en.Visible = true;
            }
            else
            {
                osdcheck.Visible = false;
                osd_panel.Visible = false;
                osdCZcheck.Visible = true;
                PUCT_en.Visible = false;
            }
            //隐藏对应按钮
            if (GetConfigValue("IsVisible") == "1")
            {
                hideEvents(true);
            }
            else
            {
                hideEvents(false);
            }
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            if (!pollingcheck.Checked)
            {
                radioGroup1.Visible = false;
            }
            else
            {
                radioGroup1.Visible = true;
            }
            //启动时清空一下之前的Flash_中间文件
            string[] files = Directory.GetFiles(Application.StartupPath + "\\Lib");
            foreach (string file in files)
            {
                if (file.Contains("Flash_"))
                {
                    File.Delete(file);
                }
            }

            //如果是这样，我们可以通过创建SynchronizationContext来简化
            if (context == null)
            {
                context = SynchronizationContext.Current;
            }
            //Bincurrency_BLL = new bincurrencyManager();
            //Serialdata_BLL = new serialdataManager();
            Task.Run(() => {
                GuidNo = Guid.NewGuid().ToString("N");
                xc151_exBll = new xc151_exManager();
                xcBaseList = JsonConvert.DeserializeObject<List<xc151>>(xc151_exBll.GetListToXc151());

                bincurrency model = new bincurrency();
                model.AddressNo = "0000";
                model.Address = "0000";
                //model.LengthAddress = "0070";
                model.LengthAddress = "0320";
                model.BinId = 1;
                model.GuidId = GuidNo;
                model.FileStatus = 2;
                model.SerialNo = 1;
                model.IsModified = 0;
                model.Reorder = 0;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

                Bincurrency_BLL.Insert(model);

                var mode102 = new bincurrency();
                mode102.GuidId = GuidNo;
                mode102.BinId = 11;
                mode102.LengthAddress = "1000";
                mode102.BinInName = $"00.txt";
                mode102.BinInPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\00.txt";
                mode102.BinOutName = $"00.txt";
                mode102.BinOutPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\00.txt";
                mode102.BinAddressNo = "00";
                mode102.BinAddressOutName = $"{Application.StartupPath}\\Lib\\XChip_Bin\\00.txt";
                mode102.SortOrder = 0;
                mode102.SerialNo = 0;
                mode102.IsModified = 0;
                mode102.AddressNo = "1000";
                mode102.Address = "1000";
                Bincurrency_BLL.Insert(mode102);

                //var model13 = new bincurrency();
                //model13.LengthAddress = "1000";
                //model13.BinId = 13;
                //model13.GuidId = GuidNo;
                //model13.IsModified = 0;
                //model13.SerialNo = 0;
                //model13.SortOrder = 0;
                ////model13.AddressNo = "2000";
                ////model13.Address = "2000";
                //model13.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                //model13.BinInName = $"PUCTFF.txt";
                //model13.BinInPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
                //model13.BinOutName = $"PUCTFF.txt";
                //model13.BinOutPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
                //Bincurrency_BLL.Insert(model13);

                RefreshGridView();
            });
            AppHelper.UpdateAppConfig("Folder_Road_Force", Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
            //Setting0_Patch.Checked = true;
        }

        private static void XChip_ToBin_Security_Load()
        {
            if (_instance.isSecurity)
            {
                _instance.osdcheck.Visible = true;
                _instance.osd_panel.Visible = true;
                _instance.osdCZcheck.Visible = false;
                _instance.osdCZcheck.Checked = false;
                _instance.PUCT_en.Visible = true;
            }
            else
            {
                _instance.osdcheck.Visible = false;
                _instance.osdcheck.Checked = false;

                _instance.osd_panel.Visible = false;
                _instance.osdCZcheck.Visible = true;

                _instance.PUCT_en.Visible = false;
                _instance.PUCT_en.Checked = false;
            }
            _instance.comboBox1.SelectedIndex = 0;
            _instance.comboBox2.SelectedIndex = 0;
            if (!_instance.pollingcheck.Checked)
            {
                _instance.radioGroup1.Visible = false;
            }
            
            //隐藏对应按钮
            if (_instance.GetConfigValue("IsSerial") == "1")
            {
                _instance.hideEvents(true);
            }
            else
            {
                _instance.hideEvents(false);
            }
            //启动时清空一下之前的Flash_中间文件
            //string[] files = Directory.GetFiles(Application.StartupPath + "\\Lib");
            //foreach (string file in files)
            //{
            //    if (file.Contains("Flash_"))
            //    {
            //        File.Delete(file);
            //    }
            //}

            //如果是这样，我们可以通过创建SynchronizationContext来简化
            if (_instance.context == null)
            {
                _instance.context = SynchronizationContext.Current;
            }
            //Bincurrency_BLL = new bincurrencyManager();
            //Serialdata_BLL = new serialdataManager();
            //Task.Run(() => {
            //    _instance.GuidNo = Guid.NewGuid().ToString("N");
            //    _instance.xc151_exBll = new xc151_exManager();
            //    _instance.xcBaseList = JsonConvert.DeserializeObject<List<xc151>>(_instance.xc151_exBll.GetListToXc151());

            //    bincurrency model = new bincurrency();
            //    model.AddressNo = "0000";
            //    model.Address = "0000";
            //    //model.LengthAddress = "0070";
            //    model.LengthAddress = "0320";
            //    model.BinId = 1;
            //    model.GuidId = _instance.GuidNo;
            //    model.FileStatus = 2;
            //    model.SerialNo = 1;
            //    model.IsModified = 0;
            //    model.Reorder = 0;
            //    model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");

            //    _instance.Bincurrency_BLL.Insert(model);

            //    var mode102 = new bincurrency();
            //    mode102.GuidId = _instance.GuidNo;
            //    mode102.BinId = 11;
            //    mode102.LengthAddress = "1000";
            //    mode102.BinInName = $"00.txt";
            //    mode102.BinInPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\00.txt";
            //    mode102.BinOutName = $"00.txt";
            //    mode102.BinOutPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\00.txt";
            //    mode102.BinAddressNo = "00";
            //    mode102.BinAddressOutName = $"{Application.StartupPath}\\Lib\\XChip_Bin\\00.txt";
            //    mode102.SortOrder = 0;
            //    mode102.SerialNo = 0;
            //    mode102.IsModified = 0;
            //    mode102.AddressNo = "1000";
            //    mode102.Address = "1000";
            //    _instance.Bincurrency_BLL.Insert(mode102);

            //    //var model13 = new bincurrency();
            //    //model13.LengthAddress = "1000";
            //    //model13.BinId = 13;
            //    //model13.GuidId = GuidNo;
            //    //model13.IsModified = 0;
            //    //model13.SerialNo = 0;
            //    //model13.SortOrder = 0;
            //    ////model13.AddressNo = "2000";
            //    ////model13.Address = "2000";
            //    //model13.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            //    //model13.BinInName = $"PUCTFF.txt";
            //    //model13.BinInPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
            //    //model13.BinOutName = $"PUCTFF.txt";
            //    //model13.BinOutPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
            //    //Bincurrency_BLL.Insert(model13);

            //    _instance.RefreshGridView();
            //});
            //AppHelper.UpdateAppConfig("Folder_Road_Force", Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
            //Setting0_Patch.Checked = true;
        }
        private void ToolBinSetting151_SendBinSetMsg(string msg)
        {
            //根据Setting文件的最大值，生成OSD保存退出区文件
            var list = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && (c.BinId == 6 || c.BinId == 7 || c.BinId == 10));
            var listOsd = list.Where(c => c.BinId == 10).ToList();
            var flagMax = SettingToTve151.SetTips151.FindLastIndex(c => c.Tips != null && c.Tips !="");
            foreach (var item in listOsd.Where(c => c.SerialNo != 0))
            {
                List<string> listStr = new List<string>();
                var f = File.ReadAllLines(item.BinInPath, Encoding.Default).ToList();
                for (int i = 0; i < flagMax + 1; i++)
                {
                    listStr.AddRange(f);
                }
                var path = System.IO.Path.GetDirectoryName(item.BinInPath);
                var name = System.IO.Path.GetFileName(item.BinInPath);
                var binPath = $"{path}\\setting_{name}";
                File.WriteAllLines(binPath, listStr, Encoding.Default);
                //var binPathout = Copy_Files_For_Header_Patch_Tool(binPath, true, "", true, false);
                //item.BinOutName = System.IO.Path.GetFileName(binPathout);
                //item.BinOutPath = binPathout;
                item.BinOutName = System.IO.Path.GetFileName(binPath);
                item.BinOutPath = binPath;
                item.LengthAddress = HeaderHelper.FilePathLengthComplement(item.BinOutPath);
                Bincurrency_BLL.Update(item);
            }
            RefreshGridView();
            AutomaticAddress(msg);
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                var list = Bincurrency_BLL.GetList(c => c.GuidId == GuidNo && c.BinId == 2);
                if (list.Count == 0)
                {
                    bincurrency model = new bincurrency();
                    //model.AddressNo = "1000";
                    //model.Address = "2000";
                    model.BinId = 2;
                    model.GuidId = GuidNo;
                    model.IsModified = 1;
                    model.FileStatus = 0;
                    model.SerialNo = 0;
                    model.SortOrder = 0;
                    model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    Bincurrency_BLL.Insert(model);
                }
                else
                {
                    
                    //bincurrency model = new bincurrency();
                    var model = list.Find(c => c.BinInPath == null);
                    //model.AddressNo = "1000";
                    //model.Address = "2000";
                    model.BinId = 2;
                    model.GuidId = GuidNo;
                    model.IsModified = 1;
                    model.SerialNo = 0;
                    model.SortOrder = 0;
                    model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    Bincurrency_BLL.Update(model);
                }

            }
            else
            {
                //Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 116);
                //Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 116);

                //Setting勾选框未勾选时，需同时删除setting区数据
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && (c.BinId == 2 || c.BinId == 3));
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            RefreshGridView();
        }
        public string config_Files_For_Header_Patch_Tool(string Inputfilepath, bool Isflash, string eepromaddr, bool isSetting, bool isHead)
        {
            string strFileName = System.IO.Path.GetFileName(Inputfilepath); //获取文件名
            string strNewSavePath = Application.StartupPath + "\\Lib\\xc151_setting\\Flash_config_" + strFileName;

            if (isHead)
            {
                Setting2FlashE2prom.FlashHeader2Flash(Inputfilepath, strNewSavePath);
            }
            else
            {
                Setting2FlashE2prom.FlashSetting2Flash(Inputfilepath, strNewSavePath, 0, 0, 0);
            }

            return strNewSavePath;
        }
        private void KeyOpen()
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "TXT文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                //读取文件内容
                List<string> strlist = Setting2Help.FileProcessing(sfd.FileName);

                //var strsfd = System.IO.File.ReadAllText(sfd.FileName.ToString()).Replace("\r\n", "").Replace("，", ",").Trim();
                //var strlist = new List<string>();
                //Regex ConnoteA = new Regex("(0x)[a-fA-F0-9]{8}");
                //foreach (var item in ConnoteA.Matches(strsfd))
                //{

                //    strlist.Add(item.ToString());
                //}
                
                if (strlist.Count() >= 2)
                {
                    
                    if (strlist[0].Length == strlist[1].Length)
                    {
                        string xcbin = string.Format("{0}\\Lib\\XChip_Bin\\{1}", Application.StartupPath, ConfigurationManager.AppSettings["XChip_Bin"]);
                        string pSavePath = System.IO.Path.GetDirectoryName(xcbin); //获取文件路径
                        //string patchSavePath = GenerateFileHelp.CreateDateTimeDay(pSavePath) + "Key_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
                        string patchSavePath = pSavePath + "\\Key_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
                        StringBuilder sb = new StringBuilder();
                        //不知道为什么加入扰码暂时去掉20230901
                        //Random rd = new Random();
                        //randomNo = rd.Next(10, 250);
                        //for (int i = 0; i < 256; i++)
                        //{
                        //    sb.Append($"0x{rd.Next().ToString("x8")},\r\n");
                        //    if (randomNo == i)
                        //    {
                        //        sb.Append($"{strlist[0]},\r\n");
                        //        i++;
                        //        sb.Append($"{strlist[1]},\r\n");
                        //        i++;
                        //    }
                        //}
                        if (2 != radioGroup2.SelectedIndex)
                        {
                            string result = string.Join("", strlist);
                            uint[] output = new uint[result.Length / 2]; // 创建与输入长度一半的uint数组

                            for (int j = 0; j < output.Length; j++)
                            {
                                string numStr = result.Substring(j * 2, 2); // 每两个字符提取一个数字字符串
                                output[j] = Convert.ToUInt32(numStr, 16); // 将数字字符串解析为uint类型并赋值给数组元素
                            }
                            //这里存入加密数据 扩张了 
                            var KeyEntryptlist = Setting2Help.KeyEntrypt(output);
                            sb.Append($"{KeyEntryptlist[1] + KeyEntryptlist[0]},\r\n");
                            sb.Append($"{KeyEntryptlist[3] + KeyEntryptlist[2]},\r\n");
                            sb.Append($"{KeyEntryptlist[5] + KeyEntryptlist[4]},\r\n");
                            sb.Append($"{KeyEntryptlist[7] + KeyEntryptlist[6]},\r\n");
                        }
                        else
                        {
                            //大小端反转
                            byte[] bTemp = new byte[4];
                            var tempUint = getUintToString(strlist[0]);
                            bTemp[0] = (byte)(tempUint & 0xff);
                            bTemp[1] = (byte)(tempUint >> 8 & 0xff);
                            bTemp[2] = (byte)(tempUint >> 16 & 0xff);
                            bTemp[3] = (byte)(tempUint >> 24 & 0xff);

                            string output = bTemp[0].ToString("X2") + bTemp[1].ToString("X2") + bTemp[2].ToString("X2") + bTemp[3].ToString("X2");

                            sb.Append($"{output},\r\n");

                            bTemp = new byte[4];
                            tempUint = getUintToString(strlist[1]);
                            bTemp[0] = (byte)(tempUint & 0xff);
                            bTemp[1] = (byte)(tempUint >> 8 & 0xff);
                            bTemp[2] = (byte)(tempUint >> 16 & 0xff);
                            bTemp[3] = (byte)(tempUint >> 24 & 0xff);
                            output = bTemp[0].ToString("X2") + bTemp[1].ToString("X2") + bTemp[2].ToString("X2") + bTemp[3].ToString("X2"); ;

                            sb.Append($"{output},\r\n");

                        }


                        

                        HeaderHelper.SavePatchText(patchSavePath, sb.ToString());//保存文件
                        Bincurrency_BLL.Delete(c => c.BinId == 12);

                        bincurrency model = new bincurrency();
                        model.BinId = 12;
                        model.GuidId = GuidNo;
                        model.IsModified = 1;
                        model.SerialNo = 0;
                        model.SortOrder = 0;
                        model.FileStatus = 2;
                        model.BinInPath = patchSavePath;
                        model.BinInName = System.IO.Path.GetFileName(patchSavePath); //获取文件名
                        model.BinOutName = System.IO.Path.GetFileName(patchSavePath); //获取文件名
                        model.BinOutPath = patchSavePath;
                        //文件长度
                        //这里不知道什么原因不需要1000所以注释掉20230901
                        // model.LengthAddress = "1000";
                        model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(model.BinOutPath);
                        Bincurrency_BLL.Insert(model);
                        AutomaticAddress(GuidNo);
                        RefreshGridView();
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("KEY文件长度有误！请检查！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无法解析文件！请输入正确KEY文件...", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void PUCT_en_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                bincurrency model = new bincurrency();
                model.BinId = 13;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 0;
                model.Reorder = 5;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 13);
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            //var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            //if (ischecked.Checked)
            //{
            //    Bincurrency_BLL.Delete(c => c.BinId == 13);
            //    bincurrency model = new bincurrency();
            //    model.LengthAddress = "1000";
            //    model.BinId = 13;
            //    model.GuidId = GuidNo;
            //    model.IsModified = 1;
            //    model.FileStatus = 0;
            //    model.SerialNo = 0;
            //    model.SortOrder = 0;
            //    model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            //    model.BinInName = $"PUCTFF.txt";
            //    model.BinInPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
            //    model.BinOutName = $"PUCTFF.txt";
            //    model.BinOutPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
            //    Bincurrency_BLL.Insert(model);
            //}
            //else
            //{
            //    Bincurrency_BLL.Delete(c => c.BinId == 13);
            //    bincurrency model = new bincurrency();
            //    model.LengthAddress = "1000";
            //    model.BinId = 13;
            //    model.GuidId = GuidNo;
            //    model.IsModified = 0;
            //    model.FileStatus = 0;
            //    model.SerialNo = 0;
            //    model.SortOrder = 0;
            //    model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            //    model.BinInName = $"PUCTFF.txt";
            //    model.BinInPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
            //    model.BinOutName = $"PUCTFF.txt";
            //    model.BinOutPath = $"{Application.StartupPath}\\Lib\\PUCTFF.txt";
            //    Bincurrency_BLL.Insert(model);
            //    //计算地址 
            //    //AutomaticAddress(GuidNo);
            //    Config_en.Checked = false;
            //}

            //byte[] binchar = new byte[] { };
            //var binHeaderchar = binHelper.HeadParse("C:\\Users\\Administrator.DESKTOP-6N69MR9\\Desktop\\数据\\测试_202306251459.bin", ref binchar);
            ////获取到对应区间地址信息
            //var ccc = Xc151BLL.GetList();
            //for (int i = 0; i < ccc.Count(); i++)
            //{
            //    ccc[i].dataexample = "0x" + binHeaderchar[i];
            //}
            ////获得该bin文件中已使能的Setting区
            //var aaa = ccc.Where(c => c.section == "索引配置区" && c.dataexample == "0x01" && c.describe.Contains("App setting区")).ToList();
            //var aaaa = Convert.ToUInt32(ccc[211].dataexample + ccc[210].dataexample.Replace("0x", "") + ccc[209].dataexample.Replace("0x", "") + ccc[208].dataexample.Replace("0x", ""), 16);

            RefreshGridView();
        }
        public string PUCT_Flash(string Inputfilepath)
        {
            string strFileName = System.IO.Path.GetFileName(Inputfilepath); //获取文件名
            string strNewSavePath = Application.StartupPath + "\\Lib\\xc151_setting\\Flash_CUPT_" + strFileName;

            Setting2FlashE2prom.FlashPUCTFlash(Inputfilepath, strNewSavePath);

            return strNewSavePath;
        }

        private void DCBL_en_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                bincurrency model = new bincurrency();
                model.BinId = 14;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 0;
                model.Reorder = 5;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 14);
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            DCBLlist = new List<string>();
            for (int i = 0; i < 8; i++)
            {
                DCBLlist.Add("0x00000000");
            }
            RefreshGridView();
        }

        private void osdCZcheck_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                //osdcheck.Enabled = false;
                bincurrency model = new bincurrency();
                model.BinId = 10;
                model.GuidId = GuidNo;
                model.IsModified = 1;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 0;
                model.Reorder = 5;
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                //osdcheck.Enabled = true;
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 10);
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            //设置是否开启使能开关
            SetXcBase(xcBaseList.Where(c => c.Id == 30).ToList()[0].address, "02", ref xcBaseList);
            //setDataexample(xcBaseList.Where(c => c.Id == 30).First().address, ischecked.Checked, ref xcBaseList);
            // 刷新界面
            RefreshGridView();
        }

        private void Log_en_CheckedChanged(object sender, EventArgs e)
        {
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.Checked)
            {
                #region 生成Boot_Log文本文件
                var LogPath = $"{Application.StartupPath}\\Lib\\XChip_Bin\\Flash_Log.txt";
                List<string> loglist = new List<string>();

                //0x2000/4是因为一次性添加4个数据
                for (int i = 0; i < 0x2000 / 4; i++)
                {
                    if (i == 0 || i == 1024)
                    {
                        loglist.Add("51014358");
                    }
                    else
                    {
                        loglist.Add("00000000");
                    }

                }
                File.WriteAllLines(LogPath, loglist);
                #endregion

                bincurrency model = new bincurrency();
                model.BinId = 15;
                model.GuidId = GuidNo;
                model.IsModified = 0;
                model.SerialNo = 0;
                model.SortOrder = 0;
                model.FileStatus = 2;
                model.Reorder = 5;
                model.BinOutPath = LogPath;
                model.BinOutName = System.IO.Path.GetFileName(LogPath);
                model.BinInPath = LogPath;
                model.BinInName = System.IO.Path.GetFileName(LogPath);
                model.LengthAddress = HeaderHelper.FilePathLengthComplementnew(LogPath);
                model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                Bincurrency_BLL.Insert(model);
            }
            else
            {
                Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 15);
                //计算地址 
                //AutomaticAddress(GuidNo);
            }
            //设置是否开启使能开关
            setDataexample(xcBaseList.Where(c => c.Id == 33).First().address, ischecked.Checked, ref xcBaseList);
            // 刷新界面
            RefreshGridView();
        }

        private void Log_btn_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入BIN（*.bin）|*.bin";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() != DialogResult.OK) return;
            string foldPath = Path.GetDirectoryName(sfd.FileName);
            AppHelper.UpdateAppConfig("Folder_Road_Force", foldPath);
            ///读取文件全部内容
            var blist = BinToList(sfd.FileName);
            int headKey = 0x368;
            //headLength是包含crc校验的长度，xclist是不包含crc校验
            int headLength = 0x320;
            //获取存放的开始地址 计算结束地址  赋值类
            var HeadStartAddr = Convert.ToUInt32("0x" + blist[headKey + 1].original.ToString("X2") + blist[headKey].original.ToString("X2"), 16);
            var HeadEndAddr = HeadStartAddr + headLength;

            //xc151binparsingManager xcm = new xc151binparsingManager();
            //var xclist = xcm.GetList();

            xc151_exManager xcmex = new xc151_exManager();
            var xclist = JsonConvert.DeserializeObject<List<xc151binparsing>>(xcmex.GetListToXc151Binparsing());
            blist = BinBaseToNode(blist, xclist);
            var blistaa = blist.Where(c => c.module != null && c.module.Contains("Boot Log存储区")).ToList();
            List<string> Loglist = new List<string>();
            NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();

            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1");

            NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
            ICellStyle RedStyle = NPOIOprateExcel.GetExcelStyle(workbook, NPOI.SS.UserModel.HorizontalAlignment.Center, VerticalAlignment.Center, NPOI.HSSF.Util.HSSFColor.DarkRed.Index, 10);
            ICellStyle GreenStyle = NPOIOprateExcel.GetExcelStyle(workbook, NPOI.SS.UserModel.HorizontalAlignment.Center, VerticalAlignment.Center, NPOI.HSSF.Util.HSSFColor.Green.Index, 10);


            headerRow.CreateCell(0).SetCellValue("Boot次数");
            //headerRow.CreateCell(0).SetCellValue("Boot次数");
            //headerRow.CreateCell(0).SetCellValue("Boot次数");
            //headerRow.CreateCell(0).SetCellValue("Boot次数");
            headerRow.CreateCell(1).SetCellValue("Boot失败次数");
            //headerRow.CreateCell(1).SetCellValue("Boot失败次数");
            //headerRow.CreateCell(1).SetCellValue("Boot失败次数");
            //headerRow.CreateCell(1).SetCellValue("Boot失败次数");
            headerRow.CreateCell(2).SetCellValue("当前Log的数量");
            //headerRow.CreateCell(3).SetCellValue("当前Log的数量");
            headerRow.CreateCell(3).SetCellValue("Reserved");
            headerRow.CreateCell(4).SetCellValue("Reserved");
            headerRow.CreateCell(5).SetCellValue("上一次Boot Log的索引号");
            //headerRow.CreateCell(6).SetCellValue("上一次Boot Log的索引号");
            //headerRow.CreateCell(6).SetCellValue("上一次Boot Log的索引号");
            //headerRow.CreateCell(6).SetCellValue("上一次Boot Log的索引号");
            int createcell = 0;
            for (int i = 0; i <= 15; i++)
            {
                if (createcell == 0)
                {
                    var aaa = blistaa[4 + i].bigdata + blistaa[4 + i].bigaddr;
                    if (8 == aaa.Length)
                    {
                        List<string> listvalue = new List<string>();
                        for (int v = 0; v < aaa.Length; v++)
                        {
                            listvalue.Add(aaa[v].ToString() + aaa[v + 1].ToString());
                            v++;
                        }
                        aaa = listvalue[3] + listvalue[2] + listvalue[1] + listvalue[0];
                    }
                    sheet.CreateRow(1).CreateCell(createcell).SetCellValue(aaa.ToString());
                    createcell++;
                    i += 3;
                }
                else if (createcell == 1 || createcell == 5)
                {
                    var aaa = blistaa[4 + i].bigdata + blistaa[4 + i].bigaddr;
                    if (8 == aaa.Length)
                    {
                        List<string> listvalue = new List<string>();
                        for (int v = 0; v < aaa.Length; v++)
                        {
                            listvalue.Add(aaa[v].ToString() + aaa[v + 1].ToString());
                            v++;
                        }
                        aaa = listvalue[3] + listvalue[2] + listvalue[1] + listvalue[0];
                    }
                    sheet.GetRow(1).CreateCell(createcell).SetCellValue(aaa.ToString());
                    createcell++;
                    i += 3;
                }
                else if (createcell == 2)
                {
                    sheet.GetRow(1).CreateCell(createcell).SetCellValue(blistaa[5 + i].original.ToString("X2") + blistaa[4 + i].original.ToString("X2"));
                    i++;
                    createcell++;
                }
                else
                {
                    var aaa = blistaa[4 + i].original.ToString("X2");
                    sheet.GetRow(1).CreateCell(createcell).SetCellValue(blistaa[4 + i].original.ToString("X2"));
                    createcell++;
                }
            }

            sheet.CreateRow(2).CreateCell(0).SetCellValue("索引号");
            sheet.GetRow(2).CreateCell(1).SetCellValue("信息区类型");
            sheet.GetRow(2).CreateCell(2).SetCellValue("0x80500133");
            sheet.GetRow(2).CreateCell(3).SetCellValue("Reserved");
            sheet.GetRow(2).CreateCell(4).SetCellValue("Reserved");
            sheet.GetRow(2).CreateCell(5).SetCellValue("0x80500138");
            sheet.GetRow(2).CreateCell(6).SetCellValue("0x80500139");
            sheet.GetRow(2).CreateCell(7).SetCellValue("0x8050013a");
            sheet.GetRow(2).CreateCell(8).SetCellValue("0x8050013b");
            sheet.GetRow(2).CreateCell(9).SetCellValue("0x8050013c");
            sheet.GetRow(2).CreateCell(10).SetCellValue("0x8050013d");
            sheet.GetRow(2).CreateCell(11).SetCellValue("0x8050013e");
            sheet.GetRow(2).CreateCell(12).SetCellValue("0x8050013f");
            int Row = 2;
            List<string> Boot_013c = new List<string>();
            List<string> Boot_0138 = new List<string>();
            for (int i = 20; i <= blistaa.Count(); i++)
            {
                if (i >= 0x1000)
                {
                    break;
                }
                if (blistaa[i].smallexample == "0x5843,0x151")
                {
                    for (int j = 0; j <= 12; j++)
                    {
                        if (blistaa[i].smallexample == "0x5843,0x151")
                        {
                            i += 4;
                            Row++;
                            var aaa = blistaa[i + j].bigdata + blistaa[i + j].bigaddr;

                            if (8 == aaa.Length)
                            {
                                List<string> listvalue = new List<string>();
                                for (int v = 0; v < aaa.Length; v++)
                                {
                                    listvalue.Add(aaa[v].ToString() + aaa[v + 1].ToString());
                                    v++;
                                }
                                aaa = listvalue[3] + listvalue[2] + listvalue[1] + listvalue[0];
                            }
                            sheet.CreateRow(Row).CreateCell(j).SetCellValue(aaa.ToString());
                            i += 3;
                        }
                        else
                        {
                            sheet.GetRow(Row).CreateCell(j).SetCellValue(blistaa[i + j].original.ToString("X2"));
                            if (j >= 9)
                            {   //8050013c
                                var aaa = blistaa[i + j];
                                Boot_013c.AddRange(FindFirstBitPosition(blistaa[i + j].original.ToString("X2")));
                            }
                            else if (j >= 5)
                            {   //80500138
                                Boot_0138.AddRange(FindFirstBitPosition(blistaa[i + j].original.ToString("X2")));
                            }

                        }
                    }
                    int cellTemp = 13;
                    Boot_0138 = Boot_0138.Distinct().ToList();
                    for (int z = 0; z < Boot_0138.Count(); z++)
                    {
                        string str = BitSetting138(Boot_0138[z]);
                        if (!string.IsNullOrEmpty(str))
                        {
                            var cellT = sheet.GetRow(Row).CreateCell(cellTemp++);
                            sheet.SetColumnWidth(cellTemp, (str.Length+10) * 256);
                            if (str.Contains("未检测") || str.Contains("异常") || str.Contains("失败") || str.Contains("错误"))
                            {
                                cellT.CellStyle = RedStyle;
                            }
                            if (str.Contains("存在") || str.Contains("通过") || str.Contains("成功") || str.Contains("完成") || str.Contains("正确"))
                            {
                                cellT.CellStyle = GreenStyle;
                            }
                            cellT.SetCellValue(str);
                        }
                        
                    }
                    Boot_013c = Boot_013c.Distinct().ToList();
                    for (int x  = 0; x < Boot_013c.Count(); x++)
                    {
                        string str = BitSetting13c(Boot_013c[x]);
                        if (!string.IsNullOrEmpty(str))
                        {
                            var cellT = sheet.GetRow(Row).CreateCell(cellTemp++);
                            sheet.SetColumnWidth(cellTemp, (str.Length+10) * 256);
                            if (str.Contains("未检测") || str.Contains("异常") || str.Contains("失败") || str.Contains("错误"))
                            {
                                cellT.CellStyle = RedStyle;
                            }
                            if (str.Contains("存在") || str.Contains("通过") || str.Contains("成功") || str.Contains("完成") || str.Contains("正确"))
                            {
                                cellT.CellStyle = GreenStyle;
                            }
                            cellT.SetCellValue(str);
                        }
                       
                    }

                    //sheet.GetRow(Row).CreateCell(13).SetCellValue(String.Join(", ", Boot_configlist.Where(x => !string.IsNullOrEmpty(x)).ToList()));
                    Boot_013c = new List<string>();
                    Boot_0138 = new List<string>();
                    i += 12;
                }


            }

            using (FileStream file = new FileStream(Path.GetDirectoryName(sfd.FileName) + $"\\{Path.GetFileNameWithoutExtension(sfd.FileName)}Log.xls", FileMode.Create, FileAccess.Write))
            {
                workbook.Write(file);
                DevExpress.XtraEditors.XtraMessageBox.Show("导出成功");
            }
        }


       

        private static UInt32 getUintToString(string addr)
        {
            if (string.IsNullOrEmpty(addr))
            {
                return 0x0;
            }
            else if (addr.Contains("0x"))
            {
                var temp = addr.Replace("0x", "").Trim();
                return Convert.ToUInt32(temp, 16);
            }
            else
            {

                return Convert.ToUInt32(addr.Trim(), 16);
            }
        }

        public List<string> FindFirstBitPosition(string hexValue)
        {
            List<string> hexValuelist = new List<string>();
            int decimalValue = int.Parse(hexValue.Replace("0x", ""), System.Globalization.NumberStyles.HexNumber);

            for (int i = 0; i < 32; i++)
            {
                int value = decimalValue & (1 << i);
                if (value != 0)
                {
                    hexValuelist.Add(i.ToString());
                }
            }
            return hexValuelist;
        }
        public string BitSetting138(String BitValuelist)
        {
            string BitValue = "";
            //for (int i = 0; i < BitValuelist.Count(); i++)
            //{
                switch (BitValuelist)
                {
                    //case "0":
                    //    {
                    //        BitValue += "检测flash和eeprom是否存在  ";
                    //    }
                    //    break;
                    //case "1":
                    //    {
                    //        BitValue += "开始读取flash中Bin文件的标识符0x58430151  ";
                    //    }
                    //    break;
                    case "2":
                        {
                            BitValue += "Flash存在  ";
                        }
                        break;
                    //case "3":
                    //    {
                    //        BitValue += "flash读取异常，尝试读取EEPROM的ID  ";
                    //    }
                    //    break;
                    //case "4":
                    //    {
                    //        BitValue += "EEPROM的ID读取成功，EEPROM存在  ";
                    //    }
                    //    break;
                    //case "5":
                    //    {
                    //        BitValue += "Rtl_Mode_GPIO4_Latch_Val为0，直接读EEPROM  ";
                    //    }
                    //    break;
                    case "6":
                        {
                            BitValue += "EEPROM存在  ";
                        }
                        break;
                    case "7":
                        {
                            BitValue += "未检测存储设备  ";
                        }
                        break;
                    case "8":
                        {
                            BitValue += "头文件CRC校验异常  ";
                        }
                        break;
                    case "9":
                        {
                            BitValue += "头文件CRC校验通过  ";
                        }
                        break;
                    //case "10":
                    //    {
                    //        BitValue += "开始加Boot Config0  ";
                    //    }
                    //    break;
                    //case "11":
                    //    {
                    //        BitValue += "开始加载补丁数据  ";
                    //    }
                    //    break;
                    //case "12":
                    //    {
                    //        BitValue += "nLoadMode正常，正式加载补丁数据  ";
                    //    }
                    //    break;
                    case "13":
                        {
                            BitValue += "Patch数据CRC校验失败  ";
                        }
                        break;
                    case "14":
                        {
                            BitValue += "Patch数据CRC校验成功  ";
                        }
                        break;
                    case "15":
                        {
                            BitValue += "Patch注册成功  ";
                        }
                        break;
                    case "16":
                        {
                            BitValue += "Patch注册地址异常，注册失败  ";
                        }
                        break;
                    //case "17":
                    //    {
                    //        BitValue += "开始执行Flash解密  ";
                    //    }
                    //    break;
                    case "18":
                        {
                            BitValue += "Flash解密成功  ";
                        }
                        break;
                    case "19":
                        {
                            BitValue += "Flash解密失败  ";
                        }
                        break;
                    //case "20":
                    //    {
                    //        BitValue += "开始加载OSD数据  ";
                    //    }
                    //    break;
                    case "21":
                        {
                            BitValue += "OSD数据加载完成  ";
                        }
                        break;
                    //case "22":
                    //    {
                    //        BitValue += "USB IQ参数存在，置USB_IQ标志为1  ";
                    //    }
                    //    break;
                    //case "23":
                    //    {
                    //        BitValue += "USB IQ参数不存在，置USB_IQ标志为0  ";
                    //    }
                    //    break;
                    //case "24":
                    //    {
                    //        BitValue += "开始加载App Code数据  ";
                    //    }
                    //    break;
                    //case "25":
                    //    {
                    //        BitValue += "nLoadMode正常，正式加载App Code数据  ";
                    //    }
                    //    break;
                    case "26":
                        {
                            BitValue += "App Code数据CRC校验失败  ";
                        }
                        break;
                    case "27":
                        {
                            BitValue += "load App Code数据完成  ";
                        }
                        break;
                    //case "28":
                    //    {
                    //        BitValue += "Xchip_FirmwareLoad函数执行完成  ";
                    //    }
                    //    break;
                    case "29":
                        {
                            BitValue += "加载完成Boot_Config1数据  ";
                        }
                        break;
                    //case "30":
                    //    {
                    //        BitValue += "注册App Code  ";
                    //    }
                    //    break;
                    //case "31":
                    //    {
                    //        BitValue += "While(1)前，固件Boot Load执行完成  ";
                    //    }
                        //break;
                    default:
                        break;
                }
            //}

            return BitValue;
        }
        public string BitSetting13c(String BitValuelist)
        {
            string BitValue = "";
            //for (int i = 0; i < BitValuelist.Count(); i++)
            //{
                switch (BitValuelist)
                {
                    case "0":
                        {
                            BitValue += "Boot_config区0区BOOT模式正确  ";
                        }
                        break;
                    case "1":
                        {
                            BitValue += "Boot_config区0区BOOT模式错误  ";
                        }
                        break;
                    case "2":
                        {
                            BitValue += "Boot_config区0区PLATFORM_ID正确  ";
                        }
                        break;
                    case "3":
                        {
                            BitValue += "Boot_config区0区PLATFORM_ID错误  ";
                        }
                        break;
                    case "4":
                        {
                            BitValue += "Boot_config区0区长度正确  ";
                        }
                        break;
                    case "5":
                        {
                            BitValue += "Boot_config区0区长度错误  ";
                        }
                        break;
                    case "6":
                        {
                            BitValue += "Boot_config区0区校验成功  ";
                        }
                        break;
                    case "7":
                        {
                            BitValue += "Boot_config区0区校验失败  ";
                        }
                        break;
                    case "8":
                        {
                            BitValue += "Boot_config区1区BOOT模式正确  ";
                        }
                        break;
                    case "9":
                        {
                            BitValue += "Boot_config区1区BOOT模式错误  ";
                        }
                        break;
                    case "10":
                        {
                            BitValue += "Boot_config区1区PLATFORM_ID正确  ";
                        }
                        break;
                    case "11":
                        {
                            BitValue += "Boot_config区1区PLATFORM_ID错误  ";
                        }
                        break;
                    case "12":
                        {
                            BitValue += "Boot_config区1区长度正确  ";
                        }
                        break;
                    case "13":
                        {
                            BitValue += "Boot_config区1区长度错误  ";
                        }
                        break;
                    case "14":
                        {
                            BitValue += "Boot_config区1区校验成功  ";
                        }
                        break;
                    case "15":
                        {
                            BitValue += "Boot_config区1区校验失败  ";
                        }
                        break;
                    //case "16":
                    //    {
                    //        BitValue += "nLoadMode正常，正式加载倒车线数据  ";
                    //    }
                    //    break;
                    case "17":
                        {
                            BitValue += "倒车线头数据CRC校验失败  ";
                        }
                        break;
                    //case "18":
                    //    {
                    //        BitValue += "开始执行倒车线配置初始化  ";
                    //    }
                    //    break;
                    case "19":
                        {
                            BitValue += "倒车线数据加载完成  ";
                        }
                        break;
                    default:
                        break;
                }
            //}

            return BitValue;
        }

        public static List<BinBase> BinToList(string path, bool isbool = false)
        {
            List<BinBase> blist = new List<BinBase>();
            try
            {
                var list = System.IO.File.ReadAllBytes(path).ToList();
                string fffd = "";
                string fffe = "";
                string fff6 = "";
                bool f6bool = false;
                double fff7 = 0;
                bool f7bool = false;
                int bigsmall = -1; //-1表示默认  0表示big 1表示small
                string exdata = string.Empty;
                for (int i = 0; i < list.Count();)
                {
                    if (i + 4 <= list.Count())
                    {
                        string bigaddrT = string.Empty;
                        string bigdataT = string.Empty;
                        string smalladdrT = string.Empty;
                        string smalldataT = string.Empty;
                        if (isbool)
                        {
                            bigaddrT = $"{list[i].ToString("X2")}{list[i + 1].ToString("X2")}";
                            bigdataT = $"{list[i + 2].ToString("X2")}{list[i + 3].ToString("X2")}";
                            smalladdrT = $"{list[i + 1].ToString("X2")}{list[i].ToString("X2")}";
                            smalldataT = $"{list[i + 3].ToString("X2")}{list[i + 2].ToString("X2")}";
                        }
                        else
                        {
                            bigaddrT = $"{list[i + 2].ToString("X2")}{list[i + 3].ToString("X2")}";
                            bigdataT = $"{list[i].ToString("X2")}{list[i + 1].ToString("X2")}";
                            smalladdrT = $"{list[i + 3].ToString("X2")}{list[i + 2].ToString("X2")}";
                            smalldataT = $"{list[i + 1].ToString("X2")}{list[i].ToString("X2")}";
                        }

                        if (bigaddrT.ToLower() == "fffd")
                        {
                            fffd = bigdataT;
                        }
                        else if (smalladdrT.ToLower() == "fffd")
                        {
                            fffd = smalldataT;
                        }
                        else if (bigaddrT.ToLower() == "fffe")
                        {
                            fffe = bigdataT;
                        }
                        else if (smalladdrT.ToLower() == "fffe")
                        {
                            fffe = smalldataT;
                        }
                        else if (bigaddrT.ToLower() == "fff6")
                        {
                            fff6 = bigdataT;
                            f6bool = true;
                            bigsmall = 0;
                        }
                        else if (smalladdrT.ToLower() == "fff6")
                        {
                            fff6 = smalldataT;
                            f6bool = true;
                            bigsmall = 1;
                        }
                        else if (bigaddrT.ToLower() == "fff5")
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                BinBase model = new BinBase();
                                model.original = list[i];
                                model.bigaddr = bigaddrT;
                                model.smalladdr = smalladdrT;
                                model.bigdata = bigdataT;
                                model.smalldata = smalldataT;
                                model.sort = j;
                                model.AnalyticalModel = exdata;
                                model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                if (!string.IsNullOrEmpty(fffd) && !string.IsNullOrEmpty(fffe))
                                {
                                    model.addresspart = $"{Convert.ToUInt16(fffd, 16).ToString("X2")}{Convert.ToUInt16(fffe, 16).ToString("X2")}";
                                }
                                blist.Add(model);
                                i++;
                            }
                            continue;
                        }
                        else if (smalladdrT.ToLower() == "fff5")
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                BinBase model = new BinBase();
                                model.original = list[i];
                                model.bigaddr = bigaddrT;
                                model.smalladdr = smalladdrT;
                                model.bigdata = bigdataT;
                                model.smalldata = smalldataT;
                                model.sort = j;
                                model.AnalyticalModel = exdata;
                                model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                if (!string.IsNullOrEmpty(fffd) && !string.IsNullOrEmpty(fffe))
                                {
                                    model.addresspart = $"{Convert.ToUInt16(fffd, 16).ToString("X2")}{Convert.ToUInt16(fffe, 16).ToString("X2")}";
                                }
                                blist.Add(model);
                                i++;
                            }
                            continue;
                        }
                        else if (bigaddrT.ToLower() == "f5f5")
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                BinBase model = new BinBase();
                                model.original = list[i];
                                model.bigaddr = bigaddrT;
                                model.smalladdr = smalladdrT;
                                model.bigdata = bigdataT;
                                model.smalldata = smalldataT;
                                model.sort = j;
                                model.AnalyticalModel = exdata;
                                model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                if (!string.IsNullOrEmpty(fffd) && !string.IsNullOrEmpty(fffe))
                                {
                                    model.addresspart = $"{Convert.ToUInt16(fffd, 16).ToString("X2")}{Convert.ToUInt16(fffe, 16).ToString("X2")}";
                                }
                                blist.Add(model);
                                i++;
                            }
                            continue;
                        }
                        else if (smalladdrT.ToLower() == "f5f5")
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                BinBase model = new BinBase();
                                model.original = list[i];
                                model.bigaddr = bigaddrT;
                                model.smalladdr = smalladdrT;
                                model.bigdata = bigdataT;
                                model.smalldata = smalldataT;
                                model.sort = j;
                                model.AnalyticalModel = exdata;
                                model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                if (!string.IsNullOrEmpty(fffd) && !string.IsNullOrEmpty(fffe))
                                {
                                    model.addresspart = $"{Convert.ToUInt16(fffd, 16).ToString("X2")}{Convert.ToUInt16(fffe, 16).ToString("X2")}";
                                }
                                blist.Add(model);
                                i++;
                            }
                            continue;
                        }

                        if (f6bool)
                        {
                            string bigaddrNT, bigdataNT, smalladdrNT, smalldataNT;
                            if (isbool)
                            {
                                bigaddrNT = $"{list[i + 4].ToString("X2")}{list[i + 1 + 4].ToString("X2")}";
                                bigdataNT = $"{list[i + 2 + 4].ToString("X2")}{list[i + 3 + 4].ToString("X2")}";
                                smalladdrNT = $"{list[i + 1 + 4].ToString("X2")}{list[i + 4].ToString("X2")}";
                                smalldataNT = $"{list[i + 3 + 4].ToString("X2")}{list[i + 2 + 4].ToString("X2")}";
                            }
                            else
                            {
                                bigaddrNT = $"{list[i + 2 + 4].ToString("X2")}{list[i + 3 + 4].ToString("X2")}";
                                bigdataNT = $"{list[i + 4].ToString("X2")}{list[i + 1 + 4].ToString("X2")}";
                                smalladdrNT = $"{list[i + 3 + 4].ToString("X2")}{list[i + 2 + 4].ToString("X2")}";
                                smalldataNT = $"{list[i + 1 + 4].ToString("X2")}{list[i + 4].ToString("X2")}";
                            }

                            if (bigaddrNT.ToLower() == "fff7")
                            {
                                fff7 = Convert.ToInt32(bigdataNT, 16);
                                f7bool = true;
                                f6bool = false;
                                bigsmall = 0;
                            }
                            if (smalladdrNT.ToLower() == "fff7")
                            {
                                fff7 = Convert.ToInt32(smalldataNT, 16);
                                f7bool = true;
                                f6bool = false;
                                bigsmall = 1;
                            }
                            string example = string.Empty;
                            exdata = string.Empty;
                            if (bigsmall == 0)
                            {
                                if (bigdataT.Substring(bigdataT.Length - 2) == "00")
                                {
                                    exdata = "00";
                                }
                                else if (bigdataT.Substring(bigdataT.Length - 2) == "01" || bigdataT.Substring(bigdataT.Length - 2) == "02")
                                {
                                    exdata = "03";
                                }
                                else if (bigdataT.Substring(bigdataT.Length - 2) == "03")
                                {
                                    exdata = "05";
                                }
                                else if (bigdataT.Substring(bigdataT.Length - 2) == "04")
                                {
                                    exdata = "06";
                                }
                                else if (bigdataT.Substring(bigdataT.Length - 2) == "05")
                                {
                                    exdata = "07";
                                }
                                example = $"0xfff8,0x{bigdataT.Substring(0, 2)},0xfffe,0x{exdata},";
                            }
                            else if (bigsmall == 1)
                            {

                                if (smalldataT.Substring(smalldataT.Length - 2) == "00")
                                {
                                    exdata = "00";
                                }
                                if (smalldataT.Substring(smalldataT.Length - 2) == "01" || smalldataT.Substring(smalldataT.Length - 2) == "02")
                                {
                                    exdata = "03";
                                }
                                else if (smalldataT.Substring(smalldataT.Length - 2) == "03")
                                {
                                    exdata = "05";
                                }
                                else if (smalldataT.Substring(smalldataT.Length - 2) == "04")
                                {
                                    exdata = "06";
                                }
                                else if (smalldataT.Substring(smalldataT.Length - 2) == "05")
                                {
                                    exdata = "07";
                                }
                                example = $"0xfff8,0x{smalldataT.Substring(0, 2)},\n0xfffe,0x{exdata},";
                            }

                            if (exdata == "00" || exdata == "03")
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    BinBase model = new BinBase();
                                    model.original = list[i];
                                    model.bigaddr = bigaddrT;
                                    model.smalladdr = smalladdrT;
                                    model.bigdata = bigdataT;
                                    model.smalldata = smalldataT;
                                    model.bigexample = example;
                                    model.smallexample = example;
                                    model.sort = j;
                                    model.AnalyticalModel = exdata;
                                    model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                    blist.Add(model);
                                    i++;
                                }
                                for (int j = 0; j < 4; j++)
                                {
                                    BinBase model = new BinBase();
                                    model.original = list[i];
                                    model.bigaddr = bigaddrNT;
                                    model.smalladdr = smalladdrNT;

                                    model.bigdata = bigdataNT;
                                    model.smalldata = smalldataNT;
                                    model.sort = j;
                                    model.AnalyticalModel = exdata;
                                    model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                    blist.Add(model);
                                    i++;
                                }
                            }
                            else
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    BinBase model = new BinBase();
                                    model.original = list[i];
                                    model.bigaddr = bigaddrT;
                                    model.smalladdr = smalladdrT;
                                    model.bigdata = bigdataT;
                                    model.smalldata = smalldataT;
                                    model.bigexample = example;
                                    model.smallexample = example;
                                    model.sort = j;
                                    model.AnalyticalModel = exdata;
                                    model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                    blist.Add(model);
                                    i++;
                                }
                                for (int j = 0; j < 4; j++)
                                {
                                    BinBase model = new BinBase();
                                    model.original = list[i];
                                    model.bigaddr = bigaddrNT;
                                    model.smalladdr = smalladdrNT;
                                    model.bigdata = bigdataNT;
                                    model.smalldata = smalldataNT;
                                    model.bigexample = example;
                                    model.smallexample = example;
                                    model.sort = j;
                                    model.AnalyticalModel = exdata;
                                    model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                    blist.Add(model);
                                    i++;
                                }
                            }


                        }
                        else if (f7bool)
                        {

                            if (exdata == "00")
                            {
                                if (isbool)
                                {
                                    bigaddrT = $"{list[i + 1].ToString("X2")}";
                                    bigdataT = $"{list[i].ToString("X2")}";
                                    smalladdrT = $"{list[i].ToString("X2")}";
                                    smalldataT = $"{list[i + 1].ToString("X2")}";
                                }
                                else
                                {
                                    bigaddrT = $"{list[i].ToString("X2")}";
                                    bigdataT = $"{list[i + 1].ToString("X2")}";
                                    smalladdrT = $"{list[i + 1].ToString("X2")}";
                                    smalldataT = $"{list[i].ToString("X2")}";
                                }
                                for (int j = 0; j < 2; j++)
                                {
                                    BinBase model = new BinBase();

                                    model.original = list[i];
                                    model.bigaddr = bigaddrT;
                                    model.smalladdr = smalladdrT;
                                    model.bigdata = bigdataT;
                                    model.smalldata = smalldataT;
                                    model.sort = j;
                                    model.AnalyticalModel = exdata;
                                    model.AddrVal = j > 0 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                    if (!string.IsNullOrEmpty(fffd) && !string.IsNullOrEmpty(fffe))
                                    {
                                        model.addresspart = $"{Convert.ToUInt16(fffd, 16).ToString("X2")}{Convert.ToUInt16(fffe, 16).ToString("X2")}";
                                    }
                                    blist.Add(model);
                                    i++;
                                }
                                fff7 -= 1;
                            }
                            else if (exdata == "03")
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    BinBase model = new BinBase();
                                    model.original = list[i];
                                    model.bigaddr = bigaddrT;
                                    model.smalladdr = smalladdrT;
                                    model.bigdata = bigdataT;
                                    model.smalldata = smalldataT;
                                    model.sort = j;
                                    model.AnalyticalModel = exdata;
                                    model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                    if (!string.IsNullOrEmpty(fffd) && !string.IsNullOrEmpty(fffe))
                                    {
                                        model.addresspart = $"{Convert.ToUInt16(fffd, 16).ToString("X2")}{Convert.ToUInt16(fffe, 16).ToString("X2")}";
                                    }
                                    blist.Add(model);
                                    i++;
                                }
                                fff7 -= 1;
                            }
                            else
                            {
                                string bigaddrNT, bigdataNT, smalladdrNT, smalldataNT;
                                if (isbool)
                                {
                                    bigaddrNT = $"{list[i + 4].ToString("X2")}{list[i + 1 + 4].ToString("X2")}";
                                    bigdataNT = $"{list[i + 2 + 4].ToString("X2")}{list[i + 3 + 4].ToString("X2")}";
                                    smalladdrNT = $"{list[i + 1 + 4].ToString("X2")}{list[i + 4].ToString("X2")}";
                                    smalldataNT = $"{list[i + 3 + 4].ToString("X2")}{list[i + 2 + 4].ToString("X2")}";
                                }
                                else
                                {
                                    bigaddrNT = $"{list[i + 2 + 4].ToString("X2")}{list[i + 3 + 4].ToString("X2")}";
                                    bigdataNT = $"{list[i + 4].ToString("X2")}{list[i + 1 + 4].ToString("X2")}";
                                    smalladdrNT = $"{list[i + 3 + 4].ToString("X2")}{list[i + 2 + 4].ToString("X2")}";
                                    smalldataNT = $"{list[i + 1 + 4].ToString("X2")}{list[i + 4].ToString("X2")}";
                                }
                                string example = string.Empty;
                                string addrEx = string.Empty;
                                if (bigsmall == 0)
                                {
                                    addrEx = bigaddrT;
                                    example = $"0xffe0,0x{bigaddrT},\n0xffe1,0x{bigdataT},\n0xffe2,0x{bigaddrNT},\n0xffe3,0x{bigdataNT},";
                                }
                                else if (bigsmall == 1)
                                {
                                    addrEx = smalladdrT;
                                    example = $"0xffe0,0x{smalladdrT},\n0xffe1,0x{smalldataT},\n0xffe2,0x{smalladdrNT},\n0xffe3,0x{smalldataNT},";
                                }
                                for (int j = 0; j < 8; j++)
                                {
                                    BinBase model = new BinBase();

                                    model.original = list[i];
                                    model.bigaddr = bigdataT;
                                    model.smalladdr = smalldataT;
                                    model.bigdata = bigaddrNT + bigdataNT;
                                    model.smalldata = smalladdrNT + smalldataNT;
                                    model.addresspart = addrEx;
                                    model.bigexample = example;
                                    model.smallexample = example;
                                    model.sort = j;
                                    model.AnalyticalModel = exdata;
                                    model.AddrVal = j > 3 ? AddressValueEnum.Val : AddressValueEnum.Addr;
                                    blist.Add(model);
                                    i++;
                                }
                                fff7 -= 2;
                            }


                            if (fff7 <= 0)
                            {
                                f7bool = false;
                                f6bool = false;
                                bigsmall = -1;
                                exdata = string.Empty;
                            }
                        }
                        else
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                BinBase model = new BinBase();
                                model.original = list[i];
                                model.bigaddr = bigaddrT;
                                model.smalladdr = smalladdrT;
                                model.bigdata = bigdataT;
                                model.smalldata = smalldataT;
                                model.sort = j;
                                model.AnalyticalModel = exdata;
                                model.AddrVal = j > 1 ? AddressValueEnum.Addr : AddressValueEnum.Val;
                                if (!string.IsNullOrEmpty(fffd) && !string.IsNullOrEmpty(fffe))
                                {
                                    model.addresspart = $"{Convert.ToUInt16(fffd, 16).ToString("X2")}{Convert.ToUInt16(fffe, 16).ToString("X2")}";
                                }
                                blist.Add(model);
                                i++;
                            }
                        }

                    }
                    else { i++; }


                }


            }
            catch (Exception ex)
            {


                throw ex;
            }

            return blist;
        }


        /// <summary>
        /// 赋值bin属性值
        /// </summary>
        /// <param name="blist"></param>
        /// <param name="xclist"></param>
        /// <returns></returns>
        public static List<BinBase> BinBaseToNode(List<BinBase> blist, List<xc151binparsing> xclist)
        {
            int headKey = 0x368;
            int headLength = 0x320;
            //解析头文件
            var HeadStartAddr = Convert.ToUInt32("0x" + blist[headKey + 1].original.ToString("X2") + blist[headKey].original.ToString("X2"), 16);
            var HeadEndAddr = HeadStartAddr + headLength;
            int no = 0;
            for (int i = Convert.ToInt32(HeadStartAddr); i < HeadEndAddr; i++)
            {
                if (i >= HeadEndAddr - 4)
                {
                    for (int j = i; j < HeadEndAddr; j++)
                    {
                        blist[j].describe = "crc";
                        blist[j].remarks = "头文件crc";
                        blist[j].crcold = blist[i].original.ToString("X") + blist[i + 1].original.ToString("X") + blist[i + 2].original.ToString("X") + blist[i + 3].original.ToString("X");
                        blist[j].crchead = HeadStartAddr.ToString();
                        blist[j].crctail = (HeadEndAddr - 4).ToString();
                        blist[j].module = "Header";
                        blist[j].note = "Header_crc";
                        blist[i].section = "Header_crc";
                    }
                    i += 2;
                }
                else
                {
                    blist[i].address = xclist[no].address;
                    blist[i].describe = xclist[no].describe;
                    blist[i].dataexample = xclist[no].dataexample;
                    blist[i].module = xclist[no].module;
                    blist[i].section = xclist[no].section;
                    blist[i].note = xclist[no].note;
                    no++;
                }
            }

            var headList = blist.Where(c => c.module == "Header" && !string.IsNullOrEmpty(c.note) && !c.note.Contains("_en") && c.smalldata != "0000").ToList();
            shead = headList.Select(c => c.note).Distinct().ToList();

            for (int i = 0; i < shead.Count(); i++)
            {

                var model = blist.FindLast(c => c.module == "Header" && c.note == shead[i] && !c.note.Contains("_crc"));
                int listAddr = 0;
                if (null != model)
                {
                    listAddr = Convert.ToInt32(model.smalldata, 16);
                }
                int listnextAddr = 0;
                if (i + 1 < shead.Count())
                {
                    var sData = blist.FindLast(c => c.module == "Header" && c.note == shead[i + 1] && !c.note.Contains("_crc"));
                    if (null == sData || sData.smalldata == "FFFF")
                    {
                        listnextAddr = blist.Count();
                    }
                    else
                    {
                        listnextAddr = Convert.ToInt32(sData.smalldata, 16);
                    }

                }
                if (listAddr > blist.Count())
                {
                    continue;
                }
                /*查找开始区域中Setting头文件  后四个字节进行数据解析 视频制式、格式、排序
                1.0 参照标准 FF F5 后面四个字节为解析数据
                2.0 对象中获取一个列表的范围，然后在这个范围内查找第一个满足条件（即 smalladdr 属性转换为小写后等于 "fff5"）的元素，并返回它的索引
                3.0  blist[indexT].bigaddr; 排序
               
                */
                string videoHex = string.Empty;
                string transferHex = string.Empty;
                string idxHex = string.Empty;

                if (shead[i].Contains("App setting区") && blist.GetRange(listAddr, listnextAddr - listAddr).Exists(c => c.smalladdr.ToLower() == "fff5"))
                {
                    var indexT = blist.GetRange(listAddr, listnextAddr - listAddr).FindIndex(c => c.smalladdr.ToLower() == "fff5") + listAddr + 4;

                    videoHex = blist[indexT].bigdata.Substring(0, 2);
                    transferHex = blist[indexT].bigdata.Substring(blist[indexT].bigdata.Length - 2);
                    idxHex = blist[indexT].bigaddr.Substring(blist[indexT].bigaddr.Length - 2);
                }

                //var addrTT = addrT + listAddr;
                //每个区域赋值属性
                for (int j = listAddr; j < listnextAddr; j++)
                {
                    blist[j].module = model.section;
                    blist[j].note = model.note;
                    blist[j].VideoHex = videoHex;
                    blist[j].TransferHex = transferHex;
                    blist[j].IdxHex = idxHex;

                    if (blist[j].smalladdr.ToLower() == "fff5")
                    {
                        blist[j].describe = "crc";
                        blist[j].remarks = $"{model.note}_crc";
                        blist[j].crcold = blist[j].smalldata;
                        blist[j].crchead = listAddr.ToString();
                        blist[j].crctail = (listAddr + 8).ToString();
                        blist[j].crclength = "8";
                    }
                    else if (blist[j].bigaddr.ToLower() == "fff5")
                    {
                        blist[j].describe = "crc";
                        blist[j].remarks = $"{model.note}_crc";
                        blist[j].crcold = blist[j].bigdata;
                        blist[j].crchead = listAddr.ToString();
                        blist[j].crctail = (listAddr + 8).ToString();
                        blist[j].crclength = "8";
                    }
                    else if (blist[j].bigaddr.ToLower() == "f5f5")
                    {
                        blist[j].describe = "crc";
                        blist[j].remarks = $"{model.note}_crc";
                        blist[j].crcold = blist[j].bigdata;
                        blist[j].crchead = j.ToString();
                        //blist[c].crctail = (listAddr + 128).ToString();
                        blist[j].crclength = "128";
                    }
                    else if (blist[j].smalladdr.ToLower() == "f5f5")
                    {
                        blist[j].describe = "crc";
                        blist[j].remarks = $"{model.note}_crc";
                        blist[j].crcold = blist[j].smalldata;
                        blist[j].crchead = j.ToString();
                        //blist[c].crctail = (listAddr + 128).ToString();
                        blist[j].crclength = "128";
                    }
                }
            }
            return blist;

        }

        public static List<string> shead;

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!Setting0_Patch.Checked)
            {
                if (Bincurrency_BLL != null && xcBaseList.Count != 0)
                {
                    Bincurrency_BLL.Delete(c => c.GuidId == GuidNo && c.BinId == 4);
                    setDataexample(xcBaseList.Where(c => c.Id == 28).First().address, false, ref xcBaseList);
                }
            }
        }

        private void pollingcheck_CheckedChanged(object sender, EventArgs e)
        {
            Setting0_0.CheckState = CheckState.Unchecked;
            radioGroup1.Visible = pollingcheck.Checked;
            ParaHelp.Bin_Press_Key.Find(p => p.PKey == "0x0b1e").PValue = $"0x01";
        }

        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //取消勾选setting
            Setting0_0.CheckState = CheckState.Unchecked;
        }
        public string UnZipFile(string TargetFile, string fileName)
        {
            string fileDir =  $"{Application.StartupPath}\\Lib\\XChip_Zip";
            string[] filePaths = Directory.GetFiles(fileDir);

            // 遍历所有文件并删除它们  
            foreach (string filePath in filePaths)
            {
                // 移除文件的只读属性  
                File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);

                File.Delete(filePath);
            }

            using (var reader = ReaderFactory.Open(new FileStream(TargetFile,FileMode.Open, FileAccess.Read)))
            {
                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        reader.WriteEntryToDirectory(fileDir);
                    }
                }
            }
            //遍历所有文件
            filePaths = Directory.GetFiles(fileDir);
            foreach (var item in filePaths)
            {
                if (item.Contains(".bin") && item.Contains(fileName))
                {
                    return item;
                }
            }

            //try
            //{
            //    RemoveReadOnlyAttributes(fileDir);
            //    Directory.Delete(fileDir, true);
            //    Directory.CreateDirectory(fileDir);
            //}
            //catch (Exception ex)
            //{
            //    return ex.Message;
            //    throw;
            //}

            //// 目标文件路径（包括新扩展名）  
            //string destinationFilePath = Path.Combine(fileDir, "XChip.zip");
            //// 复制文件到目标文件夹  
            //File.Copy(TargetFile, destinationFilePath, true); // 第三个参数表示覆盖已存在的文件  

            //TargetFile = fileDir +"\\XChip.zip";
            //string rootFile = "";
            //try
            //{
            //    if (!Directory.Exists(fileDir))
            //    {
            //        Directory.CreateDirectory(fileDir);
            //    }
            //    //读取压缩文件（zip文件），准备解压缩
            //    ZipInputStream inputstream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
            //    ZipEntry entry;
            //    string path = fileDir;
            //    //解压出来的文件保存路径
            //    string rootDir = "";
            //    //根目录下的第一个子文件夹的名称
            //    while ((entry = inputstream.GetNextEntry()) != null)
            //    {
            //        rootDir = Path.GetDirectoryName(entry.Name);
            //        //得到根目录下的第一级子文件夹的名称
            //        if (rootDir.IndexOf("\\") >= 0)
            //        {
            //            rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
            //        }
            //        string dir = Path.GetDirectoryName(entry.Name);
            //        //得到根目录下的第一级子文件夹下的子文件夹名称
            //        string fileName = Path.GetFileName(entry.Name);
            //        //根目录下的文件名称
            //        if (dir != "")
            //        {
            //            //创建根目录下的子文件夹，不限制级别
            //            if (!Directory.Exists(fileDir + "\\" + dir))
            //            {
            //                path = fileDir + "\\" + dir;
            //                //在指定的路径创建文件夹
            //                Directory.CreateDirectory(path);
            //            }
            //        }
            //        else if (dir == "" && fileName != "")
            //        {
            //            //根目录下的文件
            //            path = fileDir;
            //            rootFile = fileName;
            //        }
            //        else if (dir != "" && fileName != "")
            //        {
            //            //根目录下的第一级子文件夹下的文件
            //            if (dir.IndexOf("\\") > 0)
            //            {
            //                //指定文件保存路径
            //                path = fileDir + "\\" + dir;
            //            }
            //        }
            //        if (dir == rootDir)
            //        {
            //            //判断是不是需要保存在根目录下的文件
            //            path = fileDir + "\\" + rootDir;
            //        }

            //        //以下为解压zip文件的基本步骤
            //        //基本思路：遍历压缩文件里的所有文件，创建一个相同的文件
            //        if (fileName != String.Empty)
            //        {
            //            FileStream fs = File.Create(path + "\\" + fileName);
            //            int size = 2048;
            //            byte[] data = new byte[2048];
            //            while (true)
            //            {
            //                size = inputstream.Read(data, 0, data.Length);
            //                if (size > 0)
            //                {
            //                    fs.Write(data, 0, size);
            //                }
            //                else
            //                {
            //                    break;
            //                }
            //            }
            //            fs.Close();
            //        }
            //    }
            //    inputstream.Close();
            //    return rootFile;
            //}
            //catch (Exception ex)
            //{
            //    return ex.Message;
            //}
            return "";
        }

        //用于取消指定路径下所有文件和子文件夹的只读属性  
        public static void RemoveReadOnlyAttributes(string path)
        {
            try
            {
                // 确认路径存在  
                if (Directory.Exists(path))
                {
                    // 获取目录下的所有文件和子目录  
                    string[] files = Directory.GetFiles(path);
                    string[] subDirectories = Directory.GetDirectories(path);

                    // 遍历所有文件并取消只读属性  
                    foreach (var file in files)
                    {
                        FileInfo fileInfo = new FileInfo(file);
                        if (fileInfo.IsReadOnly)
                        {
                            fileInfo.IsReadOnly = false; // 取消只读属性  
                        }
                    }

                    // 遍历所有子目录并递归取消只读属性  
                    foreach (var subDirectory in subDirectories)
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(subDirectory);
                        if (directoryInfo.Attributes.HasFlag(FileAttributes.ReadOnly))
                        {
                            directoryInfo.Attributes &= ~FileAttributes.ReadOnly; // 取消只读属性  
                        }
                        // 递归取消子目录中所有文件和文件夹的只读属性  
                        RemoveReadOnlyAttributes(subDirectory); // 递归调用方法处理子目录中的文件和文件夹  
                    }
                }
                else if (File.Exists(path)) // 如果传入的是文件路径，则直接处理文件  
                {
                    FileInfo fileInfo = new FileInfo(path);
                    if (fileInfo.IsReadOnly)
                    {
                        fileInfo.IsReadOnly = false; // 取消只读属性  
                    }
                }
                else
                {
                    Console.WriteLine("指定的路径不存在。");
                }
            }
            catch (Exception ex)
            {
                // 输出遇到的错误信息  
                Console.WriteLine("发生错误: " + ex.Message);
            }
        }

        private void checkEdit1_CheckedChanged_1(object sender, EventArgs e)
        {
            XChip_VersionInfo xvi = new XChip_VersionInfo();
            var ischecked = sender as DevExpress.XtraEditors.CheckEdit;
            if (ischecked.CheckState != CheckState.Unchecked && xvi.ShowDialog() == DialogResult.Cancel)
            {

            }
            else
            {
                ParaHelp.CleanOsdVersionInfo();
            }
        }
    }
}
